CommentInterfaceTest

  1. drupal
    1. 8
    2. 7

Hierarchy

Properties

NameDescription
CommentHelperCase::$admin_user
CommentHelperCase::$node
CommentHelperCase::$web_user
DrupalTestCase::$assertionsAssertions thrown in that test case.
DrupalTestCase::$databasePrefixThe database prefix of this test run.
DrupalTestCase::$originalFileDirectoryThe original file directory, before it was changed for testing purposes.
DrupalTestCase::$resultsCurrent results of this test case.
DrupalTestCase::$skipClassesThis class is skipped when looking for the source of an assertion.
DrupalTestCase::$testIdThe test run ID.
DrupalTestCase::$timeLimitTime limit for the test.
DrupalWebTestCase::$additionalCurlOptionsAdditional cURL options.
DrupalWebTestCase::$contentThe content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFileThe current cookie file used by cURL.
DrupalWebTestCase::$curlHandleThe handle of the current cURL connection.
DrupalWebTestCase::$drupalSettingsThe value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elementsThe parsed version of the page.
DrupalWebTestCase::$generatedTestFilesWhether the files were copied to the test files directory.
DrupalWebTestCase::$headersThe headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentialsHTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_methodHTTP authentication method
DrupalWebTestCase::$loggedInUserThe current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacksThe original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUserThe original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContentThe content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$profileThe profile to install as a basis for testing.
DrupalWebTestCase::$redirect_countThe number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_idThe current session ID, if available.
DrupalWebTestCase::$session_nameThe current session name, if available.
DrupalWebTestCase::$urlThe URL currently loaded in the internal browser.

Functions & methods

NameDescription
CommentHelperCase::commentContactInfoAvailableCheck for contact info.
CommentHelperCase::commentExistsChecks current page for specified comment.
CommentHelperCase::deleteCommentDelete comment.
CommentHelperCase::getUnapprovedCommentGet the comment ID for an unapproved comment.
CommentHelperCase::performCommentOperationPerform the specified operation on the specified comment.
CommentHelperCase::postCommentPost comment.
CommentHelperCase::setCommentAnonymousSet comment anonymous level setting.
CommentHelperCase::setCommentFormSet comment form location setting.
CommentHelperCase::setCommentPreviewSet comment preview setting.
CommentHelperCase::setCommentSettingsSet comment setting for article content type.
CommentHelperCase::setCommentsPerPageSet the default number of comments per page.
CommentHelperCase::setCommentSubjectSet comment subject setting.
CommentHelperCase::setUp
CommentHelperCase::testCommentNewCommentsIndicatorTests new comment marker.
CommentInterfaceTest::assertCommentLinksAsserts that comment links appear according to the passed environment setup.
CommentInterfaceTest::getInfo
CommentInterfaceTest::setEnvironmentRe-configures the environment, module settings, and user permissions.
CommentInterfaceTest::testCommentInterfaceTest comment interface.
CommentInterfaceTest::testCommentLinksTests comment links.
CommentInterfaceTest::testCommentNodeCommentStatisticsTests the node comment statistics.
DrupalTestCase::assertInternal helper: stores the assert.
DrupalTestCase::assertEqualCheck to see if two values are equal.
DrupalTestCase::assertFalseCheck to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdenticalCheck to see if two values are identical.
DrupalTestCase::assertNotEqualCheck to see if two values are not equal.
DrupalTestCase::assertNotIdenticalCheck to see if two values are not identical.
DrupalTestCase::assertNotNullCheck to see if a value is not NULL.
DrupalTestCase::assertNullCheck to see if a value is NULL.
DrupalTestCase::assertTrueCheck to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssertDelete an assertion record by message ID.
DrupalTestCase::errorFire an error assertion.
DrupalTestCase::errorHandlerHandle errors during test runs.
DrupalTestCase::exceptionHandlerHandle exceptions.
DrupalTestCase::failFire an assertion that is always negative.
DrupalTestCase::generatePermutationsConverts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCallCycles through backtrace until the first non-assertion method is found.
DrupalTestCase::insertAssertStore an assertion from outside the testing context.
DrupalTestCase::passFire an assertion that is always positive.
DrupalTestCase::randomNameGenerates a random string containing letters and numbers.
DrupalTestCase::randomStringGenerates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::runRun all tests in this class.
DrupalTestCase::verboseLogs verbose message in a text file.
DrupalWebTestCase::assertFieldAsserts that a field exists with the given name or id.
DrupalWebTestCase::assertFieldByIdAsserts that a field exists in the current page with the given id and value.
DrupalWebTestCase::assertFieldByNameAsserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPathAsserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldCheckedAsserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLinkPass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHrefPass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMailAsserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPatternAsserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailStringAsserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIdsAsserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoFieldAsserts that a field does not exist with the given name or id.
DrupalWebTestCase::assertNoFieldByIdAsserts that a field does not exist with the given id and value.
DrupalWebTestCase::assertNoFieldByNameAsserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPathAsserts that a field does not exist in the current page by the given XPath.
DrupalWebTestCase::assertNoFieldCheckedAsserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLinkPass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHrefPass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelectedAsserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPatternWill trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRawPass 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::assertNoResponseAsserts the page did not return the specified response code.
DrupalWebTestCase::assertNoTextPass 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::assertNoTitlePass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueTextPass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelectedAsserts that a select option in the current page is checked.
DrupalWebTestCase::assertPatternWill trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRawPass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponseAsserts the page responds with the specified response code.
DrupalWebTestCase::assertTextPass 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::assertTextHelperHelper for assertText and assertNoText.
DrupalWebTestCase::assertTitlePass if the page title is the given string.
DrupalWebTestCase::assertUniqueTextPass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelperHelper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrlPass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQueryBuilds an XPath query.
DrupalWebTestCase::checkForMetaRefreshCheck 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::checkPermissionsCheck to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLinkFollows a link by name.
DrupalWebTestCase::constructFieldXpathHelper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::cronRunRuns cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlCloseClose the cURL handler and unset the handler.
DrupalWebTestCase::curlExecInitializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallbackReads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitializeInitializes the cURL connection.
DrupalWebTestCase::drupalCompareFilesCompare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentTypeCreates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNodeCreates a node based on default settings.
DrupalWebTestCase::drupalCreateRoleInternal helper function; Create a role with specified permissions.
DrupalWebTestCase::drupalCreateUserCreate a user with a given set of permissions. The permissions correspond to the names given on the privileges page.
DrupalWebTestCase::drupalGetRetrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAXRetrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContentGets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeaderGets 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::drupalGetHeadersGets 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::drupalGetMailsGets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitleGet a node from the database based on its title.
DrupalWebTestCase::drupalGetSettingsGets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFilesGet a list files that can be used in tests.
DrupalWebTestCase::drupalGetTokenGenerate a token for the currently logged in user.
DrupalWebTestCase::drupalHeadRetrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLoginLog in a user with the internal browser.
DrupalWebTestCase::drupalLogout
DrupalWebTestCase::drupalPostExecute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAXExecute an Ajax submission.
DrupalWebTestCase::drupalSetContentSets 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::drupalSetSettingsSets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrlTakes a path and returns an absolute path.
DrupalWebTestCase::getAllOptionsGet all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItemGet the selected value from a select field.
DrupalWebTestCase::getUrlGet the current url from the cURL handler.
DrupalWebTestCase::handleFormHandle 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::parseParse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistryPreload the registry from the testing site.
DrupalWebTestCase::refreshVariablesRefresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread.
DrupalWebTestCase::resetAllReset all data structures after having enabled new modules.
DrupalWebTestCase::tearDownDelete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix.
DrupalWebTestCase::verboseEmailOutputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpathPerform 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::__constructConstructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct

modules/comment/comment.test, line 306

View source
<?php
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, t('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), t('Comment found.'));
    $by_viewer_class = $this->xpath('//a[@id=:comment_id]/following-sibling::div[1][contains(@class, "comment-by-viewer")]', array(':comment_id' => 'comment-' . $comment->id));
    $this->assertTrue(!empty($by_viewer_class), t('HTML class for comments by viewer 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), t('Comment found.'));

    // Check comment display.
    $this->drupalGet('node/' . $this->node->nid . '/' . $comment->id);
    $this->assertText($subject_text, t('Individual comment subject found.'));
    $this->assertText($comment_text, t('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, t('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') . ')', t('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, t('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, t('Individual comment-reply subject found.'));
    $this->assertText($comment_text, t('Individual comment-reply body found.'));
    $reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
    $reply_loaded = comment_load($reply->id);
    $this->assertTrue($this->commentExists($reply, TRUE), t('Reply found.'));
    $this->assertEqual($comment->id, $reply_loaded->pid, t('Pid of a reply to a comment is set correctly.'));
    $this->assertEqual(rtrim($comment_loaded->thread, '/') . '.00/', $reply_loaded->thread, t('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, t('Individual comment-reply subject found.'));
    $this->assertText($comment_text, t('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), t('Second reply found.'));
    $this->assertEqual(rtrim($comment_loaded->thread, '/') . '.01/', $reply_loaded->thread, t('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), t('Modified reply found.'));

    // Correct link count
    $this->drupalGet('node');
    $this->assertRaw('4 comments', t('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), t('Page one exists. %s'));
    $this->drupalGet('node/' . $this->node->nid, array('query' => array('page' => 1)));
    $this->assertTrue($this->commentExists($reply, TRUE), t('Page two exists. %s'));
    $this->setCommentsPerPage(50);

    // Create comment #5 to assert HTML class.
    $comment = $this->postComment($this->node, $this->randomName(), $this->randomName());
    $by_node_author_class = $this->xpath('//a[@id=:comment_id]/following-sibling::div[1][contains(@class, "comment-by-node-author")]', array(':comment_id' => 'comment-' . $comment->id));
    $this->assertTrue(!empty($by_node_author_class), t('HTML class for node author found.'));

    // 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, t('Article node created.'));
    $this->drupalGet('comment/reply/' . $this->node->nid);
    $this->assertText('This discussion is closed', t('Posting to node with comments disabled'));
    $this->assertNoField('edit-comment', t('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, t('Article node created.'));
    $this->drupalGet('comment/reply/' . $this->node->nid);
    $this->assertText('This discussion is closed', t('Posting to node with comments read-only'));
    $this->assertNoField('edit-comment', t('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, t('Article node created.'));
    $this->drupalGet('comment/reply/' . $this->node->nid);
    $this->assertNoText('This discussion is closed', t('Posting to node with comments enabled'));
    $this->assertField('edit-comment-body-' . $langcode . '-0-value', t('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), t('Comment not found.'));
    $this->assertFalse($this->commentExists($reply, TRUE), t('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), t('Form comment found.'));

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

  /**
   * 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, t('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, t('The initial value of node last_comment_timestamp is the node created date.'));
    $this->assertEqual($node->last_comment_name, NULL, t('The initial value of node last_comment_name is NULL.'));
    $this->assertEqual($node->last_comment_uid, $this->web_user->uid, t('The initial value of node last_comment_uid is the node uid.'));
    $this->assertEqual($node->comment_count, 0, t('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, t('The value of node last_comment_name is NULL.'));
    $this->assertEqual($node->last_comment_uid, $this->web_user2->uid, t('The value of node last_comment_uid is the comment #1 uid.'));
    $this->assertEqual($node->comment_count, 1, t('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, t('The value of node last_comment_name is still NULL.'));
    $this->assertEqual($node->last_comment_uid, $this->web_user2->uid, t('The value of node last_comment_uid is still the comment #1 uid.'));
    $this->assertEqual($node->comment_count, 1, t('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, t('The value of node last_comment_name is the name of the anonymous user.'));
    $this->assertEqual($node->last_comment_uid, 0, t('The value of node last_comment_uid is zero.'));
    $this->assertEqual($node->comment_count, 2, t('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),
      // @todo Complete test coverage for:
      //'comments'        => array(COMMENT_NODE_OPEN, COMMENT_NODE_CLOSED, COMMENT_NODE_HIDDEN),
      //// COMMENT_ANONYMOUS_MUST_CONTACT is irrelevant for this test.
      //'contact '        => array(COMMENT_ANONYMOUS_MAY_CONTACT, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
    );

    $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');
          }
        }
      }
      // User is allowed 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), t('Comment form found below.'));
          }
          else {
            $this->assertFalse(count($elements), t('Comment form not found below.'));
          }
        }
      }
    }
  }
}
?>