Projet

Général

Profil

Paste
Télécharger (96,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / comment / comment.test @ 01dfd3b5

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for comment.module.
6
 */
7

    
8
class CommentHelperCase extends DrupalWebTestCase {
9
  protected $super_user;
10
  protected $admin_user;
11
  protected $web_user;
12
  protected $node;
13

    
14
  function setUp() {
15
    $modules = func_get_args();
16
    if (isset($modules[0]) && is_array($modules[0])) {
17
      $modules = $modules[0];
18
    }
19
    $modules[] = 'comment';
20
    parent::setUp($modules);
21

    
22
    // Create users and test node.
23
    $this->super_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
24
    $this->admin_user = $this->drupalCreateUser(array('administer content types', 'administer comments', 'administer blocks', 'administer actions', 'administer fields'));
25
    $this->web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'create article content', 'edit own comments'));
26
    $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->web_user->uid));
27
  }
28

    
29
  /**
30
   * Post comment.
31
   *
32
   * @param $node
33
   *   Node to post comment on.
34
   * @param $comment
35
   *   Comment body.
36
   * @param $subject
37
   *   Comment subject.
38
   * @param $contact
39
   *   Set to NULL for no contact info, TRUE to ignore success checking, and
40
   *   array of values to set contact info.
41
   */
42
  function postComment($node, $comment, $subject = '', $contact = NULL) {
43
    $langcode = LANGUAGE_NONE;
44
    $edit = array();
45
    $edit['comment_body[' . $langcode . '][0][value]'] = $comment;
46

    
47
    $preview_mode = variable_get('comment_preview_article', DRUPAL_OPTIONAL);
48
    $subject_mode = variable_get('comment_subject_field_article', 1);
49

    
50
    // Must get the page before we test for fields.
51
    if ($node !== NULL) {
52
      $this->drupalGet('comment/reply/' . $node->nid);
53
    }
54

    
55
    if ($subject_mode == TRUE) {
56
      $edit['subject'] = $subject;
57
    }
58
    else {
59
      $this->assertNoFieldByName('subject', '', 'Subject field not found.');
60
    }
61

    
62
    if ($contact !== NULL && is_array($contact)) {
63
      $edit += $contact;
64
    }
65
    switch ($preview_mode) {
66
      case DRUPAL_REQUIRED:
67
        // Preview required so no save button should be found.
68
        $this->assertNoFieldByName('op', t('Save'), 'Save button not found.');
69
        $this->drupalPost(NULL, $edit, t('Preview'));
70
        // Don't break here so that we can test post-preview field presence and
71
        // function below.
72
      case DRUPAL_OPTIONAL:
73
        $this->assertFieldByName('op', t('Preview'), 'Preview button found.');
74
        $this->assertFieldByName('op', t('Save'), 'Save button found.');
75
        $this->drupalPost(NULL, $edit, t('Save'));
76
        break;
77

    
78
      case DRUPAL_DISABLED:
79
        $this->assertNoFieldByName('op', t('Preview'), 'Preview button not found.');
80
        $this->assertFieldByName('op', t('Save'), 'Save button found.');
81
        $this->drupalPost(NULL, $edit, t('Save'));
82
        break;
83
    }
84
    $match = array();
85
    // Get comment ID
86
    preg_match('/#comment-([0-9]+)/', $this->getURL(), $match);
87

    
88
    // Get comment.
89
    if ($contact !== TRUE) { // If true then attempting to find error message.
90
      if ($subject) {
91
        $this->assertText($subject, 'Comment subject posted.');
92
      }
93
      $this->assertText($comment, 'Comment body posted.');
94
      $this->assertTrue((!empty($match) && !empty($match[1])), 'Comment id found.');
95
    }
96

    
97
    if (isset($match[1])) {
98
      return (object) array('id' => $match[1], 'subject' => $subject, 'comment' => $comment);
99
    }
100
  }
101

    
102
  /**
103
   * Checks current page for specified comment.
104
   *
105
   * @param object $comment Comment object.
106
   * @param boolean $reply The comment is a reply to another comment.
107
   * @return boolean Comment found.
108
   */
109
  function commentExists($comment, $reply = FALSE) {
110
    if ($comment && is_object($comment)) {
111
      $regex = '/' . ($reply ? '<div class="indented">(.*?)' : '');
112
      $regex .= '<a id="comment-' . $comment->id . '"(.*?)'; // Comment anchor.
113
      $regex .= '<div(.*?)'; // Begin in comment div.
114
      $regex .= $comment->subject . '(.*?)'; // Match subject.
115
      $regex .= $comment->comment . '(.*?)'; // Match comment.
116
      $regex .= '/s';
117

    
118
      return (boolean)preg_match($regex, $this->drupalGetContent());
119
    }
120
    else {
121
      return FALSE;
122
    }
123
  }
124

    
125
  /**
126
   * Delete comment.
127
   *
128
   * @param object $comment
129
   *   Comment to delete.
130
   */
131
  function deleteComment($comment) {
132
    $this->drupalPost('comment/' . $comment->id . '/delete', array(), t('Delete'));
133
    $this->assertText(t('The comment and all its replies have been deleted.'), 'Comment deleted.');
134
  }
135

    
136
  /**
137
   * Set comment subject setting.
138
   *
139
   * @param boolean $enabled
140
   *   Subject value.
141
   */
142
  function setCommentSubject($enabled) {
143
    $this->setCommentSettings('comment_subject_field', ($enabled ? '1' : '0'), 'Comment subject ' . ($enabled ? 'enabled' : 'disabled') . '.');
144
  }
145

    
146
  /**
147
   * Set comment preview setting.
148
   *
149
   * @param int $mode
150
   *   Preview value.
151
   */
152
  function setCommentPreview($mode) {
153
    switch ($mode) {
154
      case DRUPAL_DISABLED:
155
        $mode_text = 'disabled';
156
        break;
157

    
158
      case DRUPAL_OPTIONAL:
159
        $mode_text = 'optional';
160
        break;
161

    
162
      case DRUPAL_REQUIRED:
163
        $mode_text = 'required';
164
        break;
165
    }
166
    $this->setCommentSettings('comment_preview', $mode, format_string('Comment preview @mode_text.', array('@mode_text' => $mode_text)));
167
  }
168

    
169
  /**
170
   * Set comment form location setting.
171
   *
172
   * @param boolean $enabled
173
   *   Form value.
174
   */
175
  function setCommentForm($enabled) {
176
    $this->setCommentSettings('comment_form_location', ($enabled ? COMMENT_FORM_BELOW : COMMENT_FORM_SEPARATE_PAGE), 'Comment controls ' . ($enabled ? 'enabled' : 'disabled') . '.');
177
  }
178

    
179
  /**
180
   * Set comment anonymous level setting.
181
   *
182
   * @param integer $level
183
   *   Anonymous level.
184
   */
185
  function setCommentAnonymous($level) {
186
    $this->setCommentSettings('comment_anonymous', $level, format_string('Anonymous commenting set to level @level.', array('@level' => $level)));
187
  }
188

    
189
  /**
190
   * Set the default number of comments per page.
191
   *
192
   * @param integer $comments
193
   *   Comments per page value.
194
   */
195
  function setCommentsPerPage($number) {
196
    $this->setCommentSettings('comment_default_per_page', $number, format_string('Number of comments per page set to @number.', array('@number' => $number)));
197
  }
198

    
199
  /**
200
   * Set comment setting for article content type.
201
   *
202
   * @param string $name
203
   *   Name of variable.
204
   * @param string $value
205
   *   Value of variable.
206
   * @param string $message
207
   *   Status message to display.
208
   */
209
  function setCommentSettings($name, $value, $message) {
210
    variable_set($name . '_article', $value);
211
    // Display status message.
212
    $this->pass($message);
213
  }
214

    
215
  /**
216
   * Check for contact info.
217
   *
218
   * @return boolean Contact info is available.
219
   */
220
  function commentContactInfoAvailable() {
221
    return preg_match('/(input).*?(name="name").*?(input).*?(name="mail").*?(input).*?(name="homepage")/s', $this->drupalGetContent());
222
  }
223

    
224
  /**
225
   * Perform the specified operation on the specified comment.
226
   *
227
   * @param object $comment
228
   *   Comment to perform operation on.
229
   * @param string $operation
230
   *   Operation to perform.
231
   * @param boolean $aproval
232
   *   Operation is found on approval page.
233
   */
234
  function performCommentOperation($comment, $operation, $approval = FALSE) {
235
    $edit = array();
236
    $edit['operation'] = $operation;
237
    $edit['comments[' . $comment->id . ']'] = TRUE;
238
    $this->drupalPost('admin/content/comment' . ($approval ? '/approval' : ''), $edit, t('Update'));
239

    
240
    if ($operation == 'delete') {
241
      $this->drupalPost(NULL, array(), t('Delete comments'));
242
      $this->assertRaw(format_plural(1, 'Deleted 1 comment.', 'Deleted @count comments.'), format_string('Operation @operation was performed on comment.', array('@operation' => $operation)));
243
    }
244
    else {
245
      $this->assertText(t('The update has been performed.'), format_string('Operation @operation was performed on comment.', array('@operation' => $operation)));
246
    }
247
  }
248

    
249
  /**
250
   * Get the comment ID for an unapproved comment.
251
   *
252
   * @param string $subject
253
   *   Comment subject to find.
254
   * @return integer
255
   *   Comment id.
256
   */
257
  function getUnapprovedComment($subject) {
258
    $this->drupalGet('admin/content/comment/approval');
259
    preg_match('/href="(.*?)#comment-([^"]+)"(.*?)>(' . $subject . ')/', $this->drupalGetContent(), $match);
260

    
261
    return $match[2];
262
  }
263
}
264

    
265
class CommentInterfaceTest extends CommentHelperCase {
266
  public static function getInfo() {
267
    return array(
268
      'name' => 'Comment interface',
269
      'description' => 'Test comment user interfaces.',
270
      'group' => 'Comment',
271
    );
272
  }
273

    
274
  /**
275
   * Test comment interface.
276
   */
277
  function testCommentInterface() {
278
    $langcode = LANGUAGE_NONE;
279
    // Set comments to have subject and preview disabled.
280
    $this->drupalLogin($this->admin_user);
281
    $this->setCommentPreview(DRUPAL_DISABLED);
282
    $this->setCommentForm(TRUE);
283
    $this->setCommentSubject(FALSE);
284
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
285
    $this->drupalLogout();
286

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

    
294
    // Set comments to have subject and preview to required.
295
    $this->drupalLogout();
296
    $this->drupalLogin($this->admin_user);
297
    $this->setCommentSubject(TRUE);
298
    $this->setCommentPreview(DRUPAL_REQUIRED);
299
    $this->drupalLogout();
300

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

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

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

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

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

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

    
339
    $this->drupalLogout();
340

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

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

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

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

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

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

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

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

    
400
    // Delete comment and make sure that reply is also removed.
401
    $this->drupalLogout();
402
    $this->drupalLogin($this->admin_user);
403
    $this->deleteComment($comment);
404
    $this->deleteComment($comment_new_page);
405

    
406
    $this->drupalGet('node/' . $this->node->nid);
407
    $this->assertFalse($this->commentExists($comment), 'Comment not found.');
408
    $this->assertFalse($this->commentExists($reply, TRUE), 'Reply not found.');
409

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

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

    
421
    // Disable comment form on node page.
422
    $this->drupalLogout();
423
    $this->drupalLogin($this->admin_user);
424
    $this->setCommentForm(FALSE);
425
  }
426

    
427
  /**
428
   * Tests new comment marker.
429
   */
430
  public function testCommentNewCommentsIndicator() {
431
    // Test if the right links are displayed when no comment is present for the
432
    // node.
433
    $this->drupalLogin($this->admin_user);
434
    $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'comment' => COMMENT_NODE_OPEN));
435
    $this->drupalGet('node');
436
    $this->assertNoLink(t('@count comments', array('@count' => 0)));
437
    $this->assertNoLink(t('@count new comments', array('@count' => 0)));
438
    $this->assertLink(t('Read more'));
439
    $count = $this->xpath('//div[@id=:id]/div[@class=:class]/ul/li', array(':id' => 'node-' . $this->node->nid, ':class' => 'link-wrapper'));
440
    $this->assertTrue(count($count) == 1, 'One child found');
441

    
442
    // Create a new comment. This helper function may be run with different
443
    // comment settings so use comment_save() to avoid complex setup.
444
    $comment = (object) array(
445
      'cid' => NULL,
446
      'nid' => $this->node->nid,
447
      'node_type' => $this->node->type,
448
      'pid' => 0,
449
      'uid' => $this->loggedInUser->uid,
450
      'status' => COMMENT_PUBLISHED,
451
      'subject' => $this->randomName(),
452
      'hostname' => ip_address(),
453
      'language' => LANGUAGE_NONE,
454
      'comment_body' => array(LANGUAGE_NONE => array($this->randomName())),
455
    );
456
    comment_save($comment);
457
    $this->drupalLogout();
458

    
459
    // Log in with 'web user' and check comment links.
460
    $this->drupalLogin($this->web_user);
461
    $this->drupalGet('node');
462
    $this->assertLink(t('1 new comment'));
463
    $this->clickLink(t('1 new comment'));
464
    $this->assertRaw('<a id="new"></a>', 'Found "new" marker.');
465
    $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.');
466

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

    
477
  /**
478
   * Tests CSS classes on comments.
479
   */
480
  function testCommentClasses() {
481
    // Create all permutations for comments, users, and nodes.
482
    $parameters = array(
483
      'node_uid' => array(0, $this->web_user->uid),
484
      'comment_uid' => array(0, $this->web_user->uid, $this->admin_user->uid),
485
      'comment_status' => array(COMMENT_PUBLISHED, COMMENT_NOT_PUBLISHED),
486
      'user' => array('anonymous', 'authenticated', 'admin'),
487
    );
488
    $permutations = $this->generatePermutations($parameters);
489

    
490
    foreach ($permutations as $case) {
491
      // Create a new node.
492
      $node = $this->drupalCreateNode(array('type' => 'article', 'uid' => $case['node_uid']));
493

    
494
      // Add a comment.
495
      $comment = (object) array(
496
        'cid' => NULL,
497
        'nid' => $node->nid,
498
        'pid' => 0,
499
        'uid' => $case['comment_uid'],
500
        'status' => $case['comment_status'],
501
        'subject' => $this->randomName(),
502
        'language' => LANGUAGE_NONE,
503
        'comment_body' => array(LANGUAGE_NONE => array($this->randomName())),
504
      );
505
      comment_save($comment);
506

    
507
      // Adjust the current/viewing user.
508
      switch ($case['user']) {
509
        case 'anonymous':
510
          $this->drupalLogout();
511
          $case['user_uid'] = 0;
512
          break;
513

    
514
        case 'authenticated':
515
          $this->drupalLogin($this->web_user);
516
          $case['user_uid'] = $this->web_user->uid;
517
          break;
518

    
519
        case 'admin':
520
          $this->drupalLogin($this->admin_user);
521
          $case['user_uid'] = $this->admin_user->uid;
522
          break;
523
      }
524
      // Request the node with the comment.
525
      $this->drupalGet('node/' . $node->nid);
526

    
527
      // Verify classes if the comment is visible for the current user.
528
      if ($case['comment_status'] == COMMENT_PUBLISHED || $case['user'] == 'admin') {
529
        // Verify the comment-by-anonymous class.
530
        $comments = $this->xpath('//*[contains(@class, "comment-by-anonymous")]');
531
        if ($case['comment_uid'] == 0) {
532
          $this->assertTrue(count($comments) == 1, 'comment-by-anonymous class found.');
533
        }
534
        else {
535
          $this->assertFalse(count($comments), 'comment-by-anonymous class not found.');
536
        }
537

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

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

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

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

    
572
          // Request the node again. The comment-new class should disappear.
573
          $this->drupalGet('node/' . $node->nid);
574
          $comments = $this->xpath('//*[contains(@class, "comment-new")]');
575
          $this->assertFalse(count($comments), 'comment-new class not found.');
576
        }
577
        else {
578
          $this->assertFalse(count($comments), 'comment-new class not found.');
579
        }
580
      }
581
    }
582
  }
583

    
584
  /**
585
   * Tests the node comment statistics.
586
   */
587
  function testCommentNodeCommentStatistics() {
588
    $langcode = LANGUAGE_NONE;
589
    // Set comments to have subject and preview disabled.
590
    $this->drupalLogin($this->admin_user);
591
    $this->setCommentPreview(DRUPAL_DISABLED);
592
    $this->setCommentForm(TRUE);
593
    $this->setCommentSubject(FALSE);
594
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
595
    $this->drupalLogout();
596

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

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

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

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

    
620
    // Prepare for anonymous comment submission (comment approval enabled).
621
    variable_set('user_register', USER_REGISTER_VISITORS);
622
    $this->drupalLogin($this->admin_user);
623
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
624
      'access comments' => TRUE,
625
      'post comments' => TRUE,
626
      'skip comment approval' => FALSE,
627
    ));
628
    // Ensure that the poster can leave some contact info.
629
    $this->setCommentAnonymous('1');
630
    $this->drupalLogout();
631

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

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

    
645
    // Prepare for anonymous comment submission (no approval required).
646
    $this->drupalLogin($this->admin_user);
647
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
648
      'access comments' => TRUE,
649
      'post comments' => TRUE,
650
      'skip comment approval' => TRUE,
651
    ));
652
    $this->drupalLogout();
653

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

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

    
667
  /**
668
   * Tests comment links.
669
   *
670
   * The output of comment links depends on various environment conditions:
671
   * - Various Comment module configuration settings, user registration
672
   *   settings, and user access permissions.
673
   * - Whether the user is authenticated or not, and whether any comments exist.
674
   *
675
   * To account for all possible cases, this test creates permutations of all
676
   * possible conditions and tests the expected appearance of comment links in
677
   * each environment.
678
   */
679
  function testCommentLinks() {
680
    // Bartik theme alters comment links, so use a different theme.
681
    theme_enable(array('garland'));
682
    variable_set('theme_default', 'garland');
683

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

    
688
    // Matrix of possible environmental conditions and configuration settings.
689
    // See setEnvironment() for details.
690
    $conditions = array(
691
      'authenticated'   => array(FALSE, TRUE),
692
      'comment count'   => array(FALSE, TRUE),
693
      'access comments' => array(0, 1),
694
      'post comments'   => array(0, 1),
695
      'form'            => array(COMMENT_FORM_BELOW, COMMENT_FORM_SEPARATE_PAGE),
696
      // USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL is irrelevant for this
697
      // test; there is only a difference between open and closed registration.
698
      'user_register'   => array(USER_REGISTER_VISITORS, USER_REGISTER_ADMINISTRATORS_ONLY),
699
      // @todo Complete test coverage for:
700
      //'comments'        => array(COMMENT_NODE_OPEN, COMMENT_NODE_CLOSED, COMMENT_NODE_HIDDEN),
701
      //// COMMENT_ANONYMOUS_MUST_CONTACT is irrelevant for this test.
702
      //'contact '        => array(COMMENT_ANONYMOUS_MAY_CONTACT, COMMENT_ANONYMOUS_MAYNOT_CONTACT),
703
    );
704

    
705
    $environments = $this->generatePermutations($conditions);
706
    foreach ($environments as $info) {
707
      $this->assertCommentLinks($info);
708
    }
709
  }
710

    
711
  /**
712
   * Re-configures the environment, module settings, and user permissions.
713
   *
714
   * @param $info
715
   *   An associative array describing the environment to setup:
716
   *   - Environment conditions:
717
   *     - authenticated: Boolean whether to test with $this->web_user or
718
   *       anonymous.
719
   *     - comment count: Boolean whether to test with a new/unread comment on
720
   *       $this->node or no comments.
721
   *   - Configuration settings:
722
   *     - form: COMMENT_FORM_BELOW or COMMENT_FORM_SEPARATE_PAGE.
723
   *     - user_register: USER_REGISTER_ADMINISTRATORS_ONLY or
724
   *       USER_REGISTER_VISITORS.
725
   *     - contact: COMMENT_ANONYMOUS_MAY_CONTACT or
726
   *       COMMENT_ANONYMOUS_MAYNOT_CONTACT.
727
   *     - comments: COMMENT_NODE_OPEN, COMMENT_NODE_CLOSED, or
728
   *       COMMENT_NODE_HIDDEN.
729
   *   - User permissions:
730
   *     These are granted or revoked for the user, according to the
731
   *     'authenticated' flag above. Pass 0 or 1 as parameter values. See
732
   *     user_role_change_permissions().
733
   *     - access comments
734
   *     - post comments
735
   *     - skip comment approval
736
   *     - edit own comments
737
   */
738
  function setEnvironment(array $info) {
739
    static $current;
740

    
741
    // Apply defaults to initial environment.
742
    if (!isset($current)) {
743
      $current = array(
744
        'authenticated' => FALSE,
745
        'comment count' => FALSE,
746
        'form' => COMMENT_FORM_BELOW,
747
        'user_register' => USER_REGISTER_VISITORS,
748
        'contact' => COMMENT_ANONYMOUS_MAY_CONTACT,
749
        'comments' => COMMENT_NODE_OPEN,
750
        'access comments' => 0,
751
        'post comments' => 0,
752
        // Enabled by default, because it's irrelevant for this test.
753
        'skip comment approval' => 1,
754
        'edit own comments' => 0,
755
      );
756
    }
757
    // Complete new environment with current environment.
758
    $info = array_merge($current, $info);
759

    
760
    // Change environment conditions.
761
    if ($current['authenticated'] != $info['authenticated']) {
762
      if ($this->loggedInUser) {
763
        $this->drupalLogout();
764
      }
765
      else {
766
        $this->drupalLogin($this->web_user);
767
      }
768
    }
769
    if ($current['comment count'] != $info['comment count']) {
770
      if ($info['comment count']) {
771
        // Create a comment via CRUD API functionality, since
772
        // $this->postComment() relies on actual user permissions.
773
        $comment = (object) array(
774
          'cid' => NULL,
775
          'nid' => $this->node->nid,
776
          'node_type' => $this->node->type,
777
          'pid' => 0,
778
          'uid' => 0,
779
          'status' => COMMENT_PUBLISHED,
780
          'subject' => $this->randomName(),
781
          'hostname' => ip_address(),
782
          'language' => LANGUAGE_NONE,
783
          'comment_body' => array(LANGUAGE_NONE => array($this->randomName())),
784
        );
785
        comment_save($comment);
786
        $this->comment = $comment;
787

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

    
799
    // Change comment settings.
800
    variable_set('comment_form_location_' . $this->node->type, $info['form']);
801
    variable_set('comment_anonymous_' . $this->node->type, $info['contact']);
802
    if ($this->node->comment != $info['comments']) {
803
      $this->node->comment = $info['comments'];
804
      node_save($this->node);
805
    }
806

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

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

    
815
    // Output verbose debugging information.
816
    // @see DrupalTestCase::error()
817
    $t_form = array(
818
      COMMENT_FORM_BELOW => 'below',
819
      COMMENT_FORM_SEPARATE_PAGE => 'separate page',
820
    );
821
    $t_contact = array(
822
      COMMENT_ANONYMOUS_MAY_CONTACT => 'optional',
823
      COMMENT_ANONYMOUS_MAYNOT_CONTACT => 'disabled',
824
      COMMENT_ANONYMOUS_MUST_CONTACT => 'required',
825
    );
826
    $t_comments = array(
827
      COMMENT_NODE_OPEN => 'open',
828
      COMMENT_NODE_CLOSED => 'closed',
829
      COMMENT_NODE_HIDDEN => 'hidden',
830
    );
831
    $verbose = $info;
832
    $verbose['form'] = $t_form[$info['form']];
833
    $verbose['contact'] = $t_contact[$info['contact']];
834
    $verbose['comments'] = $t_comments[$info['comments']];
835
    $message = t('Changed environment:<pre>@verbose</pre>', array(
836
      '@verbose' => var_export($verbose, TRUE),
837
    ));
838
    $this->assert('debug', $message, 'Debug');
839

    
840
    // Update current environment.
841
    $current = $info;
842

    
843
    return $info;
844
  }
845

    
846
  /**
847
   * Asserts that comment links appear according to the passed environment setup.
848
   *
849
   * @param $info
850
   *   An associative array describing the environment to pass to
851
   *   setEnvironment().
852
   */
853
  function assertCommentLinks(array $info) {
854
    $info = $this->setEnvironment($info);
855

    
856
    $nid = $this->node->nid;
857

    
858
    foreach (array('', "node/$nid") as $path) {
859
      $this->drupalGet($path);
860

    
861
      // User is allowed to view comments.
862
      if ($info['access comments']) {
863
        if ($path == '') {
864
          // In teaser view, a link containing the comment count is always
865
          // expected.
866
          if ($info['comment count']) {
867
            $this->assertLink(t('1 comment'));
868

    
869
            // For logged in users, a link containing the amount of new/unread
870
            // comments is expected.
871
            // See important note about comment_num_new() below.
872
            if ($this->loggedInUser && isset($this->comment) && !isset($this->comment->seen)) {
873
              $this->assertLink(t('1 new comment'));
874
              $this->comment->seen = TRUE;
875
            }
876
          }
877
        }
878
      }
879
      else {
880
        $this->assertNoLink(t('1 comment'));
881
        $this->assertNoLink(t('1 new comment'));
882
      }
883
      // comment_num_new() is based on node views, so comments are marked as
884
      // read when a node is viewed, regardless of whether we have access to
885
      // comments.
886
      if ($path == "node/$nid" && $this->loggedInUser && isset($this->comment)) {
887
        $this->comment->seen = TRUE;
888
      }
889

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

    
894
        // Anonymous users should see a note to log in or register in case
895
        // authenticated users are allowed to post comments.
896
        // @see theme_comment_post_forbidden()
897
        if (!$this->loggedInUser) {
898
          if (user_access('post comments', $this->web_user)) {
899
            // The note depends on whether users are actually able to register.
900
            if ($info['user_register']) {
901
              $this->assertText('Log in or register to post comments');
902
            }
903
            else {
904
              $this->assertText('Log in to post comments');
905
            }
906
          }
907
          else {
908
            $this->assertNoText('Log in or register to post comments');
909
            $this->assertNoText('Log in to post comments');
910
          }
911
        }
912
      }
913
      // User is allowed to post comments.
914
      else {
915
        $this->assertNoText('Log in or register to post comments');
916

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

    
926
        // Also verify that the comment form appears according to the configured
927
        // location.
928
        if ($path == "node/$nid") {
929
          $elements = $this->xpath('//form[@id=:id]', array(':id' => 'comment-form'));
930
          if ($info['form'] == COMMENT_FORM_BELOW) {
931
            $this->assertTrue(count($elements), 'Comment form found below.');
932
          }
933
          else {
934
            $this->assertFalse(count($elements), 'Comment form not found below.');
935
          }
936
        }
937
      }
938
    }
939
  }
940
}
941

    
942
/**
943
 * Test previewing comments.
944
 */
945
class CommentPreviewTest extends CommentHelperCase {
946
  public static function getInfo() {
947
    return array(
948
      'name' => 'Comment preview',
949
      'description' => 'Test comment preview.',
950
      'group' => 'Comment',
951
    );
952
  }
953

    
954
  /**
955
   * Test comment preview.
956
   */
957
  function testCommentPreview() {
958
    $langcode = LANGUAGE_NONE;
959

    
960
    // As admin user, configure comment settings.
961
    $this->drupalLogin($this->admin_user);
962
    $this->setCommentPreview(DRUPAL_OPTIONAL);
963
    $this->setCommentForm(TRUE);
964
    $this->setCommentSubject(TRUE);
965
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
966
    $this->drupalLogout();
967

    
968
    // Login as web user and add a signature and a user picture.
969
    $this->drupalLogin($this->web_user);
970
    variable_set('user_signatures', 1);
971
    variable_set('user_pictures', 1);
972
    $test_signature = $this->randomName();
973
    $edit['signature[value]'] = '<a href="http://example.com/">' . $test_signature. '</a>';
974
    $edit['signature[format]'] = 'filtered_html';
975
    $image = current($this->drupalGetTestFiles('image'));
976
    $edit['files[picture_upload]'] = drupal_realpath($image->uri);
977
    $this->drupalPost('user/' . $this->web_user->uid . '/edit', $edit, t('Save'));
978

    
979
    // As the web user, fill in the comment form and preview the comment.
980
    $edit = array();
981
    $edit['subject'] = $this->randomName(8);
982
    $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
983
    $this->drupalPost('node/' . $this->node->nid, $edit, t('Preview'));
984

    
985
    // Check that the preview is displaying the title and body.
986
    $this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".');
987
    $this->assertText($edit['subject'], 'Subject displayed.');
988
    $this->assertText($edit['comment_body[' . $langcode . '][0][value]'], 'Comment displayed.');
989

    
990
    // Check that the title and body fields are displayed with the correct values.
991
    $this->assertFieldByName('subject', $edit['subject'], 'Subject field displayed.');
992
    $this->assertFieldByName('comment_body[' . $langcode . '][0][value]', $edit['comment_body[' . $langcode . '][0][value]'], 'Comment field displayed.');
993

    
994
    // Check that the signature is displaying with the correct text format.
995
    $this->assertLink($test_signature);
996

    
997
    // Check that the user picture is displayed.
998
    $this->assertFieldByXPath("//div[contains(@class, 'comment-preview')]//div[contains(@class, 'user-picture')]//img", NULL, 'User picture displayed.');
999
  }
1000

    
1001
  /**
1002
   * Test comment edit, preview, and save.
1003
   */
1004
  function testCommentEditPreviewSave() {
1005
    $langcode = LANGUAGE_NONE;
1006
    $web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'skip comment approval'));
1007
    $this->drupalLogin($this->admin_user);
1008
    $this->setCommentPreview(DRUPAL_OPTIONAL);
1009
    $this->setCommentForm(TRUE);
1010
    $this->setCommentSubject(TRUE);
1011
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
1012

    
1013
    $edit = array();
1014
    $edit['subject'] = $this->randomName(8);
1015
    $edit['comment_body[' . $langcode . '][0][value]'] = $this->randomName(16);
1016
    $edit['name'] = $web_user->name;
1017
    $edit['date'] = '2008-03-02 17:23 +0300';
1018
    $raw_date = strtotime($edit['date']);
1019
    $expected_text_date = format_date($raw_date);
1020
    $expected_form_date = format_date($raw_date, 'custom', 'Y-m-d H:i O');
1021
    $comment = $this->postComment($this->node, $edit['subject'], $edit['comment_body[' . $langcode . '][0][value]'], TRUE);
1022
    $this->drupalPost('comment/' . $comment->id . '/edit', $edit, t('Preview'));
1023

    
1024
    // Check that the preview is displaying the subject, comment, author and date correctly.
1025
    $this->assertTitle(t('Preview comment | Drupal'), 'Page title is "Preview comment".');
1026
    $this->assertText($edit['subject'], 'Subject displayed.');
1027
    $this->assertText($edit['comment_body[' . $langcode . '][0][value]'], 'Comment displayed.');
1028
    $this->assertText($edit['name'], 'Author displayed.');
1029
    $this->assertText($expected_text_date, 'Date displayed.');
1030

    
1031
    // Check that the subject, comment, author and date fields are displayed with the correct values.
1032
    $this->assertFieldByName('subject', $edit['subject'], 'Subject field displayed.');
1033
    $this->assertFieldByName('comment_body[' . $langcode . '][0][value]', $edit['comment_body[' . $langcode . '][0][value]'], 'Comment field displayed.');
1034
    $this->assertFieldByName('name', $edit['name'], 'Author field displayed.');
1035
    $this->assertFieldByName('date', $edit['date'], 'Date field displayed.');
1036

    
1037
    // Check that saving a comment produces a success message.
1038
    $this->drupalPost('comment/' . $comment->id . '/edit', $edit, t('Save'));
1039
    $this->assertText(t('Your comment has been posted.'), 'Comment posted.');
1040

    
1041
    // Check that the comment fields are correct after loading the saved comment.
1042
    $this->drupalGet('comment/' . $comment->id . '/edit');
1043
    $this->assertFieldByName('subject', $edit['subject'], 'Subject field displayed.');
1044
    $this->assertFieldByName('comment_body[' . $langcode . '][0][value]', $edit['comment_body[' . $langcode . '][0][value]'], 'Comment field displayed.');
1045
    $this->assertFieldByName('name', $edit['name'], 'Author field displayed.');
1046
    $this->assertFieldByName('date', $expected_form_date, 'Date field displayed.');
1047

    
1048
    // Submit the form using the displayed values.
1049
    $displayed = array();
1050
    $displayed['subject'] = (string) current($this->xpath("//input[@id='edit-subject']/@value"));
1051
    $displayed['comment_body[' . $langcode . '][0][value]'] = (string) current($this->xpath("//textarea[@id='edit-comment-body-" . $langcode . "-0-value']"));
1052
    $displayed['name'] = (string) current($this->xpath("//input[@id='edit-name']/@value"));
1053
    $displayed['date'] = (string) current($this->xpath("//input[@id='edit-date']/@value"));
1054
    $this->drupalPost('comment/' . $comment->id . '/edit', $displayed, t('Save'));
1055

    
1056
    // Check that the saved comment is still correct.
1057
    $comment_loaded = comment_load($comment->id);
1058
    $this->assertEqual($comment_loaded->subject, $edit['subject'], 'Subject loaded.');
1059
    $this->assertEqual($comment_loaded->comment_body[$langcode][0]['value'], $edit['comment_body[' . $langcode . '][0][value]'], 'Comment body loaded.');
1060
    $this->assertEqual($comment_loaded->name, $edit['name'], 'Name loaded.');
1061
    $this->assertEqual($comment_loaded->created, $raw_date, 'Date loaded.');
1062

    
1063
  }
1064

    
1065
}
1066

    
1067
class CommentAnonymous extends CommentHelperCase {
1068
  public static function getInfo() {
1069
    return array(
1070
      'name' => 'Anonymous comments',
1071
      'description' => 'Test anonymous comments.',
1072
      'group' => 'Comment',
1073
    );
1074
  }
1075

    
1076
  function setUp() {
1077
    parent::setUp();
1078
    variable_set('user_register', USER_REGISTER_VISITORS);
1079
  }
1080

    
1081
  /**
1082
   * Test anonymous comment functionality.
1083
   */
1084
  function testAnonymous() {
1085
    $this->drupalLogin($this->admin_user);
1086
    // Enabled anonymous user comments.
1087
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1088
      'access comments' => TRUE,
1089
      'post comments' => TRUE,
1090
      'skip comment approval' => TRUE,
1091
    ));
1092
    $this->setCommentAnonymous('0'); // Ensure that doesn't require contact info.
1093
    $this->drupalLogout();
1094

    
1095
    // Post anonymous comment without contact info.
1096
    $anonymous_comment1 = $this->postComment($this->node, $this->randomName(), $this->randomName());
1097
    $this->assertTrue($this->commentExists($anonymous_comment1), 'Anonymous comment without contact info found.');
1098

    
1099
    // Allow contact info.
1100
    $this->drupalLogin($this->admin_user);
1101
    $this->setCommentAnonymous('1');
1102

    
1103
    // Attempt to edit anonymous comment.
1104
    $this->drupalGet('comment/' . $anonymous_comment1->id . '/edit');
1105
    $edited_comment = $this->postComment(NULL, $this->randomName(), $this->randomName());
1106
    $this->assertTrue($this->commentExists($edited_comment, FALSE), 'Modified reply found.');
1107
    $this->drupalLogout();
1108

    
1109
    // Post anonymous comment with contact info (optional).
1110
    $this->drupalGet('comment/reply/' . $this->node->nid);
1111
    $this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
1112

    
1113
    $anonymous_comment2 = $this->postComment($this->node, $this->randomName(), $this->randomName());
1114
    $this->assertTrue($this->commentExists($anonymous_comment2), 'Anonymous comment with contact info (optional) found.');
1115

    
1116
    // Ensure anonymous users cannot post in the name of registered users.
1117
    $langcode = LANGUAGE_NONE;
1118
    $edit = array(
1119
      'name' => $this->admin_user->name,
1120
      'mail' => $this->randomName() . '@example.com',
1121
      'subject' => $this->randomName(),
1122
      "comment_body[$langcode][0][value]" => $this->randomName(),
1123
    );
1124
    $this->drupalPost('comment/reply/' . $this->node->nid, $edit, t('Save'));
1125
    $this->assertText(t('The name you used belongs to a registered user.'));
1126

    
1127
    // Require contact info.
1128
    $this->drupalLogin($this->admin_user);
1129
    $this->setCommentAnonymous('2');
1130
    $this->drupalLogout();
1131

    
1132
    // Try to post comment with contact info (required).
1133
    $this->drupalGet('comment/reply/' . $this->node->nid);
1134
    $this->assertTrue($this->commentContactInfoAvailable(), 'Contact information available.');
1135

    
1136
    $anonymous_comment3 = $this->postComment($this->node, $this->randomName(), $this->randomName(), TRUE);
1137
    // Name should have 'Anonymous' for value by default.
1138
    $this->assertText(t('E-mail field is required.'), 'E-mail required.');
1139
    $this->assertFalse($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) not found.');
1140

    
1141
    // Post comment with contact info (required).
1142
    $author_name = $this->randomName();
1143
    $author_mail = $this->randomName() . '@example.com';
1144
    $anonymous_comment3 = $this->postComment($this->node, $this->randomName(), $this->randomName(), array('name' => $author_name, 'mail' => $author_mail));
1145
    $this->assertTrue($this->commentExists($anonymous_comment3), 'Anonymous comment with contact info (required) found.');
1146

    
1147
    // Make sure the user data appears correctly when editing the comment.
1148
    $this->drupalLogin($this->admin_user);
1149
    $this->drupalGet('comment/' . $anonymous_comment3->id . '/edit');
1150
    $this->assertRaw($author_name, "The anonymous user's name is correct when editing the comment.");
1151
    $this->assertRaw($author_mail, "The anonymous user's e-mail address is correct when editing the comment.");
1152

    
1153
    // Unpublish comment.
1154
    $this->performCommentOperation($anonymous_comment3, 'unpublish');
1155

    
1156
    $this->drupalGet('admin/content/comment/approval');
1157
    $this->assertRaw('comments[' . $anonymous_comment3->id . ']', 'Comment was unpublished.');
1158

    
1159
    // Publish comment.
1160
    $this->performCommentOperation($anonymous_comment3, 'publish', TRUE);
1161

    
1162
    $this->drupalGet('admin/content/comment');
1163
    $this->assertRaw('comments[' . $anonymous_comment3->id . ']', 'Comment was published.');
1164

    
1165
    // Delete comment.
1166
    $this->performCommentOperation($anonymous_comment3, 'delete');
1167

    
1168
    $this->drupalGet('admin/content/comment');
1169
    $this->assertNoRaw('comments[' . $anonymous_comment3->id . ']', 'Comment was deleted.');
1170
    $this->drupalLogout();
1171

    
1172
    // Reset.
1173
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1174
      'access comments' => FALSE,
1175
      'post comments' => FALSE,
1176
      'skip comment approval' => FALSE,
1177
    ));
1178

    
1179
    // Attempt to view comments while disallowed.
1180
    // NOTE: if authenticated user has permission to post comments, then a
1181
    // "Login or register to post comments" type link may be shown.
1182
    $this->drupalGet('node/' . $this->node->nid);
1183
    $this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
1184
    $this->assertNoLink('Add new comment', 'Link to add comment was found.');
1185

    
1186
    // Attempt to view node-comment form while disallowed.
1187
    $this->drupalGet('comment/reply/' . $this->node->nid);
1188
    $this->assertText('You are not authorized to post comments', 'Error attempting to post comment.');
1189
    $this->assertNoFieldByName('subject', '', 'Subject field not found.');
1190
    $this->assertNoFieldByName("comment_body[$langcode][0][value]", '', 'Comment field not found.');
1191

    
1192
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1193
      'access comments' => TRUE,
1194
      'post comments' => FALSE,
1195
      'skip comment approval' => FALSE,
1196
    ));
1197
    $this->drupalGet('node/' . $this->node->nid);
1198
    $this->assertPattern('@<h2[^>]*>Comments</h2>@', 'Comments were displayed.');
1199
    $this->assertLink('Log in', 1, 'Link to log in was found.');
1200
    $this->assertLink('register', 1, 'Link to register was found.');
1201

    
1202
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1203
      'access comments' => FALSE,
1204
      'post comments' => TRUE,
1205
      'skip comment approval' => TRUE,
1206
    ));
1207
    $this->drupalGet('node/' . $this->node->nid);
1208
    $this->assertNoPattern('@<h2[^>]*>Comments</h2>@', 'Comments were not displayed.');
1209
    $this->assertFieldByName('subject', '', 'Subject field found.');
1210
    $this->assertFieldByName("comment_body[$langcode][0][value]", '', 'Comment field found.');
1211

    
1212
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $anonymous_comment3->id);
1213
    $this->assertText('You are not authorized to view comments', 'Error attempting to post reply.');
1214
    $this->assertNoText($author_name, 'Comment not displayed.');
1215
  }
1216
}
1217

    
1218
/**
1219
 * Verify pagination of comments.
1220
 */
1221
class CommentPagerTest extends CommentHelperCase {
1222

    
1223
  public static function getInfo() {
1224
    return array(
1225
      'name' => 'Comment paging settings',
1226
      'description' => 'Test paging of comments and their settings.',
1227
      'group' => 'Comment',
1228
    );
1229
  }
1230

    
1231
  /**
1232
   * Confirm comment paging works correctly with flat and threaded comments.
1233
   */
1234
  function testCommentPaging() {
1235
    $this->drupalLogin($this->admin_user);
1236

    
1237
    // Set comment variables.
1238
    $this->setCommentForm(TRUE);
1239
    $this->setCommentSubject(TRUE);
1240
    $this->setCommentPreview(DRUPAL_DISABLED);
1241

    
1242
    // Create a node and three comments.
1243
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
1244
    $comments = array();
1245
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1246
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1247
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1248

    
1249
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_FLAT, 'Comment paging changed.');
1250

    
1251
    // Set comments to one per page so that we are able to test paging without
1252
    // needing to insert large numbers of comments.
1253
    $this->setCommentsPerPage(1);
1254

    
1255
    // Check the first page of the node, and confirm the correct comments are
1256
    // shown.
1257
    $this->drupalGet('node/' . $node->nid);
1258
    $this->assertRaw(t('next'), 'Paging links found.');
1259
    $this->assertTrue($this->commentExists($comments[0]), 'Comment 1 appears on page 1.');
1260
    $this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 1.');
1261
    $this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 1.');
1262

    
1263
    // Check the second page.
1264
    $this->drupalGet('node/' . $node->nid, array('query' => array('page' => 1)));
1265
    $this->assertTrue($this->commentExists($comments[1]), 'Comment 2 appears on page 2.');
1266
    $this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 2.');
1267
    $this->assertFalse($this->commentExists($comments[2]), 'Comment 3 does not appear on page 2.');
1268

    
1269
    // Check the third page.
1270
    $this->drupalGet('node/' . $node->nid, array('query' => array('page' => 2)));
1271
    $this->assertTrue($this->commentExists($comments[2]), 'Comment 3 appears on page 3.');
1272
    $this->assertFalse($this->commentExists($comments[0]), 'Comment 1 does not appear on page 3.');
1273
    $this->assertFalse($this->commentExists($comments[1]), 'Comment 2 does not appear on page 3.');
1274

    
1275
    // Post a reply to the oldest comment and test again.
1276
    $replies = array();
1277
    $oldest_comment = reset($comments);
1278
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $oldest_comment->id);
1279
    $reply = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1280

    
1281
    $this->setCommentsPerPage(2);
1282
    // We are still in flat view - the replies should not be on the first page,
1283
    // even though they are replies to the oldest comment.
1284
    $this->drupalGet('node/' . $node->nid, array('query' => array('page' => 0)));
1285
    $this->assertFalse($this->commentExists($reply, TRUE), 'In flat mode, reply does not appear on page 1.');
1286

    
1287
    // If we switch to threaded mode, the replies on the oldest comment
1288
    // should be bumped to the first page and comment 6 should be bumped
1289
    // to the second page.
1290
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Switched to threaded mode.');
1291
    $this->drupalGet('node/' . $node->nid, array('query' => array('page' => 0)));
1292
    $this->assertTrue($this->commentExists($reply, TRUE), 'In threaded mode, reply appears on page 1.');
1293
    $this->assertFalse($this->commentExists($comments[1]), 'In threaded mode, comment 2 has been bumped off of page 1.');
1294

    
1295
    // If (# replies > # comments per page) in threaded expanded view,
1296
    // the overage should be bumped.
1297
    $reply2 = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1298
    $this->drupalGet('node/' . $node->nid, array('query' => array('page' => 0)));
1299
    $this->assertFalse($this->commentExists($reply2, TRUE), 'In threaded mode where # replies > # comments per page, the newest reply does not appear on page 1.');
1300

    
1301
    $this->drupalLogout();
1302
  }
1303

    
1304
  /**
1305
   * Test comment ordering and threading.
1306
   */
1307
  function testCommentOrderingThreading() {
1308
    $this->drupalLogin($this->admin_user);
1309

    
1310
    // Set comment variables.
1311
    $this->setCommentForm(TRUE);
1312
    $this->setCommentSubject(TRUE);
1313
    $this->setCommentPreview(DRUPAL_DISABLED);
1314

    
1315
    // Display all the comments on the same page.
1316
    $this->setCommentsPerPage(1000);
1317

    
1318
    // Create a node and three comments.
1319
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
1320
    $comments = array();
1321
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1322
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1323
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1324

    
1325
    // Post a reply to the second comment.
1326
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[1]->id);
1327
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1328

    
1329
    // Post a reply to the first comment.
1330
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[0]->id);
1331
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1332

    
1333
    // Post a reply to the last comment.
1334
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[2]->id);
1335
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1336

    
1337
    // Post a reply to the second comment.
1338
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[3]->id);
1339
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1340

    
1341
    // At this point, the comment tree is:
1342
    // - 0
1343
    //   - 4
1344
    // - 1
1345
    //   - 3
1346
    //     - 6
1347
    // - 2
1348
    //   - 5
1349

    
1350
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_FLAT, 'Comment paging changed.');
1351

    
1352
    $expected_order = array(
1353
      0,
1354
      1,
1355
      2,
1356
      3,
1357
      4,
1358
      5,
1359
      6,
1360
    );
1361
    $this->drupalGet('node/' . $node->nid);
1362
    $this->assertCommentOrder($comments, $expected_order);
1363

    
1364
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Switched to threaded mode.');
1365

    
1366
    $expected_order = array(
1367
      0,
1368
      4,
1369
      1,
1370
      3,
1371
      6,
1372
      2,
1373
      5,
1374
    );
1375
    $this->drupalGet('node/' . $node->nid);
1376
    $this->assertCommentOrder($comments, $expected_order);
1377
  }
1378

    
1379
  /**
1380
   * Helper function: assert that the comments are displayed in the correct order.
1381
   *
1382
   * @param $comments
1383
   *   And array of comments.
1384
   * @param $expected_order
1385
   *   An array of keys from $comments describing the expected order.
1386
   */
1387
  function assertCommentOrder(array $comments, array $expected_order) {
1388
    $expected_cids = array();
1389

    
1390
    // First, rekey the expected order by cid.
1391
    foreach ($expected_order as $key) {
1392
      $expected_cids[] = $comments[$key]->id;
1393
    }
1394

    
1395
    $comment_anchors = $this->xpath('//a[starts-with(@id,"comment-")]');
1396
    $result_order = array();
1397
    foreach ($comment_anchors as $anchor) {
1398
      $result_order[] = substr($anchor['id'], 8);
1399
    }
1400

    
1401
    return $this->assertIdentical($expected_cids, $result_order, format_string('Comment order: expected @expected, returned @returned.', array('@expected' => implode(',', $expected_cids), '@returned' => implode(',', $result_order))));
1402
  }
1403

    
1404
  /**
1405
   * Test comment_new_page_count().
1406
   */
1407
  function testCommentNewPageIndicator() {
1408
    $this->drupalLogin($this->admin_user);
1409

    
1410
    // Set comment variables.
1411
    $this->setCommentForm(TRUE);
1412
    $this->setCommentSubject(TRUE);
1413
    $this->setCommentPreview(DRUPAL_DISABLED);
1414

    
1415
    // Set comments to one per page so that we are able to test paging without
1416
    // needing to insert large numbers of comments.
1417
    $this->setCommentsPerPage(1);
1418

    
1419
    // Create a node and three comments.
1420
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
1421
    $comments = array();
1422
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1423
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1424
    $comments[] = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1425

    
1426
    // Post a reply to the second comment.
1427
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[1]->id);
1428
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1429

    
1430
    // Post a reply to the first comment.
1431
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[0]->id);
1432
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1433

    
1434
    // Post a reply to the last comment.
1435
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $comments[2]->id);
1436
    $comments[] = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
1437

    
1438
    // At this point, the comment tree is:
1439
    // - 0
1440
    //   - 4
1441
    // - 1
1442
    //   - 3
1443
    // - 2
1444
    //   - 5
1445

    
1446
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_FLAT, 'Comment paging changed.');
1447

    
1448
    $expected_pages = array(
1449
      1 => 5, // Page of comment 5
1450
      2 => 4, // Page of comment 4
1451
      3 => 3, // Page of comment 3
1452
      4 => 2, // Page of comment 2
1453
      5 => 1, // Page of comment 1
1454
      6 => 0, // Page of comment 0
1455
    );
1456

    
1457
    $node = node_load($node->nid);
1458
    foreach ($expected_pages as $new_replies => $expected_page) {
1459
      $returned = comment_new_page_count($node->comment_count, $new_replies, $node);
1460
      $returned_page = is_array($returned) ? $returned['page'] : 0;
1461
      $this->assertIdentical($expected_page, $returned_page, format_string('Flat mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page)));
1462
    }
1463

    
1464
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Switched to threaded mode.');
1465

    
1466
    $expected_pages = array(
1467
      1 => 5, // Page of comment 5
1468
      2 => 1, // Page of comment 4
1469
      3 => 1, // Page of comment 4
1470
      4 => 1, // Page of comment 4
1471
      5 => 1, // Page of comment 4
1472
      6 => 0, // Page of comment 0
1473
    );
1474

    
1475
    $node = node_load($node->nid);
1476
    foreach ($expected_pages as $new_replies => $expected_page) {
1477
      $returned = comment_new_page_count($node->comment_count, $new_replies, $node);
1478
      $returned_page = is_array($returned) ? $returned['page'] : 0;
1479
      $this->assertEqual($expected_page, $returned_page, format_string('Threaded mode, @new replies: expected page @expected, returned page @returned.', array('@new' => $new_replies, '@expected' => $expected_page, '@returned' => $returned_page)));
1480
    }
1481
  }
1482
}
1483

    
1484
/**
1485
 * Tests comments with node access.
1486
 *
1487
 * See http://drupal.org/node/886752 -- verify there is no PostgreSQL error when
1488
 * viewing a node with threaded comments (a comment and a reply), if a node
1489
 * access module is in use.
1490
 */
1491
class CommentNodeAccessTest extends CommentHelperCase {
1492
  public static function getInfo() {
1493
    return array(
1494
      'name' => 'Comment node access',
1495
      'description' => 'Test comment viewing with node access.',
1496
      'group' => 'Comment',
1497
    );
1498
  }
1499

    
1500
  function setUp() {
1501
    parent::setUp('search', 'node_access_test');
1502
    node_access_rebuild();
1503

    
1504
    // Create users and test node.
1505
    $this->admin_user = $this->drupalCreateUser(array('administer content types', 'administer comments', 'administer blocks'));
1506
    $this->web_user = $this->drupalCreateUser(array('access comments', 'post comments', 'create article content', 'edit own comments', 'node test view'));
1507
    $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->web_user->uid));
1508
  }
1509

    
1510
  /**
1511
   * Test that threaded comments can be viewed.
1512
   */
1513
  function testThreadedCommentView() {
1514
    $langcode = LANGUAGE_NONE;
1515
    // Set comments to have subject required and preview disabled.
1516
    $this->drupalLogin($this->admin_user);
1517
    $this->setCommentPreview(DRUPAL_DISABLED);
1518
    $this->setCommentForm(TRUE);
1519
    $this->setCommentSubject(TRUE);
1520
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
1521
    $this->drupalLogout();
1522

    
1523
    // Post comment.
1524
    $this->drupalLogin($this->web_user);
1525
    $comment_text = $this->randomName();
1526
    $comment_subject = $this->randomName();
1527
    $comment = $this->postComment($this->node, $comment_text, $comment_subject);
1528
    $comment_loaded = comment_load($comment->id);
1529
    $this->assertTrue($this->commentExists($comment), 'Comment found.');
1530

    
1531
    // Check comment display.
1532
    $this->drupalGet('node/' . $this->node->nid . '/' . $comment->id);
1533
    $this->assertText($comment_subject, 'Individual comment subject found.');
1534
    $this->assertText($comment_text, 'Individual comment body found.');
1535

    
1536
    // Reply to comment, creating second comment.
1537
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
1538
    $reply_text = $this->randomName();
1539
    $reply_subject = $this->randomName();
1540
    $reply = $this->postComment(NULL, $reply_text, $reply_subject, TRUE);
1541
    $reply_loaded = comment_load($reply->id);
1542
    $this->assertTrue($this->commentExists($reply, TRUE), 'Reply found.');
1543

    
1544
    // Go to the node page and verify comment and reply are visible.
1545
    $this->drupalGet('node/' . $this->node->nid);
1546
    $this->assertText($comment_text);
1547
    $this->assertText($comment_subject);
1548
    $this->assertText($reply_text);
1549
    $this->assertText($reply_subject);
1550
  }
1551
}
1552

    
1553
class CommentApprovalTest extends CommentHelperCase {
1554
  public static function getInfo() {
1555
    return array(
1556
      'name' => 'Comment approval',
1557
      'description' => 'Test comment approval functionality.',
1558
      'group' => 'Comment',
1559
    );
1560
  }
1561

    
1562
  /**
1563
   * Test comment approval functionality through admin/content/comment.
1564
   */
1565
  function testApprovalAdminInterface() {
1566
    // Set anonymous comments to require approval.
1567
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1568
      'access comments' => TRUE,
1569
      'post comments' => TRUE,
1570
      'skip comment approval' => FALSE,
1571
    ));
1572
    $this->drupalLogin($this->admin_user);
1573
    $this->setCommentAnonymous('0'); // Ensure that doesn't require contact info.
1574

    
1575
    // Test that the comments page loads correctly when there are no comments
1576
    $this->drupalGet('admin/content/comment');
1577
    $this->assertText(t('No comments available.'));
1578

    
1579
    $this->drupalLogout();
1580

    
1581
    // Post anonymous comment without contact info.
1582
    $subject = $this->randomName();
1583
    $body = $this->randomName();
1584
    $this->postComment($this->node, $body, $subject, TRUE); // Set $contact to true so that it won't check for id and message.
1585
    $this->assertText(t('Your comment has been queued for review by site administrators and will be published after approval.'), 'Comment requires approval.');
1586

    
1587
    // Get unapproved comment id.
1588
    $this->drupalLogin($this->admin_user);
1589
    $anonymous_comment4 = $this->getUnapprovedComment($subject);
1590
    $anonymous_comment4 = (object) array('id' => $anonymous_comment4, 'subject' => $subject, 'comment' => $body);
1591
    $this->drupalLogout();
1592

    
1593
    $this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
1594

    
1595
    // Approve comment.
1596
    $this->drupalLogin($this->admin_user);
1597
    $this->performCommentOperation($anonymous_comment4, 'publish', TRUE);
1598
    $this->drupalLogout();
1599

    
1600
    $this->drupalGet('node/' . $this->node->nid);
1601
    $this->assertTrue($this->commentExists($anonymous_comment4), 'Anonymous comment visible.');
1602

    
1603
    // Post 2 anonymous comments without contact info.
1604
    $comments[] = $this->postComment($this->node, $this->randomName(), $this->randomName(), TRUE);
1605
    $comments[] = $this->postComment($this->node, $this->randomName(), $this->randomName(), TRUE);
1606

    
1607
    // Publish multiple comments in one operation.
1608
    $this->drupalLogin($this->admin_user);
1609
    $this->drupalGet('admin/content/comment/approval');
1610
    $this->assertText(t('Unapproved comments (@count)', array('@count' => 2)), 'Two unapproved comments waiting for approval.');
1611
    $edit = array(
1612
      "comments[{$comments[0]->id}]" => 1,
1613
      "comments[{$comments[1]->id}]" => 1,
1614
    );
1615
    $this->drupalPost(NULL, $edit, t('Update'));
1616
    $this->assertText(t('Unapproved comments (@count)', array('@count' => 0)), 'All comments were approved.');
1617

    
1618
    // Delete multiple comments in one operation.
1619
    $edit = array(
1620
      'operation' => 'delete',
1621
      "comments[{$comments[0]->id}]" => 1,
1622
      "comments[{$comments[1]->id}]" => 1,
1623
      "comments[{$anonymous_comment4->id}]" => 1,
1624
    );
1625
    $this->drupalPost(NULL, $edit, t('Update'));
1626
    $this->assertText(t('Are you sure you want to delete these comments and all their children?'), 'Confirmation required.');
1627
    $this->drupalPost(NULL, $edit, t('Delete comments'));
1628
    $this->assertText(t('No comments available.'), 'All comments were deleted.');
1629
  }
1630

    
1631
  /**
1632
   * Test comment approval functionality through node interface.
1633
   */
1634
  function testApprovalNodeInterface() {
1635
    // Set anonymous comments to require approval.
1636
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1637
      'access comments' => TRUE,
1638
      'post comments' => TRUE,
1639
      'skip comment approval' => FALSE,
1640
    ));
1641
    $this->drupalLogin($this->admin_user);
1642
    $this->setCommentAnonymous('0'); // Ensure that doesn't require contact info.
1643
    $this->drupalLogout();
1644

    
1645
    // Post anonymous comment without contact info.
1646
    $subject = $this->randomName();
1647
    $body = $this->randomName();
1648
    $this->postComment($this->node, $body, $subject, TRUE); // Set $contact to true so that it won't check for id and message.
1649
    $this->assertText(t('Your comment has been queued for review by site administrators and will be published after approval.'), 'Comment requires approval.');
1650

    
1651
    // Get unapproved comment id.
1652
    $this->drupalLogin($this->admin_user);
1653
    $anonymous_comment4 = $this->getUnapprovedComment($subject);
1654
    $anonymous_comment4 = (object) array('id' => $anonymous_comment4, 'subject' => $subject, 'comment' => $body);
1655
    $this->drupalLogout();
1656

    
1657
    $this->assertFalse($this->commentExists($anonymous_comment4), 'Anonymous comment was not published.');
1658

    
1659
    // Approve comment.
1660
    $this->drupalLogin($this->admin_user);
1661
    $this->drupalGet('comment/1/approve');
1662
    $this->assertResponse(403, 'Forged comment approval was denied.');
1663
    $this->drupalGet('comment/1/approve', array('query' => array('token' => 'forged')));
1664
    $this->assertResponse(403, 'Forged comment approval was denied.');
1665
    $this->drupalGet('node/' . $this->node->nid);
1666
    $this->clickLink(t('approve'));
1667
    $this->drupalLogout();
1668

    
1669
    $this->drupalGet('node/' . $this->node->nid);
1670
    $this->assertTrue($this->commentExists($anonymous_comment4), 'Anonymous comment visible.');
1671
  }
1672
}
1673

    
1674
/**
1675
 * Functional tests for the comment module blocks.
1676
 */
1677
class CommentBlockFunctionalTest extends CommentHelperCase {
1678
  public static function getInfo() {
1679
    return array(
1680
      'name' => 'Comment blocks',
1681
      'description' => 'Test comment block functionality.',
1682
      'group' => 'Comment',
1683
    );
1684
  }
1685

    
1686
  /**
1687
   * Test the recent comments block.
1688
   */
1689
  function testRecentCommentBlock() {
1690
    $this->drupalLogin($this->admin_user);
1691

    
1692
    // Set the block to a region to confirm block is available.
1693
    $edit = array(
1694
      'blocks[comment_recent][region]' => 'sidebar_first',
1695
    );
1696
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1697
    $this->assertText(t('The block settings have been updated.'), 'Block saved to first sidebar region.');
1698

    
1699
    // Set block title and variables.
1700
    $block = array(
1701
      'title' => $this->randomName(),
1702
      'comment_block_count' => 2,
1703
    );
1704
    $this->drupalPost('admin/structure/block/manage/comment/recent/configure', $block, t('Save block'));
1705
    $this->assertText(t('The block configuration has been saved.'), 'Block saved.');
1706

    
1707
    // Add some test comments, one without a subject.
1708
    $comment1 = $this->postComment($this->node, $this->randomName(), $this->randomName());
1709
    $comment2 = $this->postComment($this->node, $this->randomName(), $this->randomName());
1710
    $comment3 = $this->postComment($this->node, $this->randomName());
1711

    
1712
    // Test that a user without the 'access comments' permission cannot see the
1713
    // block.
1714
    $this->drupalLogout();
1715
    user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('access comments'));
1716
    $this->drupalGet('');
1717
    $this->assertNoText($block['title'], 'Block was not found.');
1718
    user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array('access comments'));
1719

    
1720
    // Test that a user with the 'access comments' permission can see the
1721
    // block.
1722
    $this->drupalLogin($this->web_user);
1723
    $this->drupalGet('');
1724
    $this->assertText($block['title'], 'Block was found.');
1725

    
1726
    // Test the only the 2 latest comments are shown and in the proper order.
1727
    $this->assertNoText($comment1->subject, 'Comment not found in block.');
1728
    $this->assertText($comment2->subject, 'Comment found in block.');
1729
    $this->assertText($comment3->comment, 'Comment found in block.');
1730
    $this->assertTrue(strpos($this->drupalGetContent(), $comment3->comment) < strpos($this->drupalGetContent(), $comment2->subject), 'Comments were ordered correctly in block.');
1731

    
1732
    // Set the number of recent comments to show to 10.
1733
    $this->drupalLogout();
1734
    $this->drupalLogin($this->admin_user);
1735
    $block = array(
1736
      'comment_block_count' => 10,
1737
    );
1738
    $this->drupalPost('admin/structure/block/manage/comment/recent/configure', $block, t('Save block'));
1739
    $this->assertText(t('The block configuration has been saved.'), 'Block saved.');
1740

    
1741
    // Post an additional comment.
1742
    $comment4 = $this->postComment($this->node, $this->randomName(), $this->randomName());
1743

    
1744
    // Test that all four comments are shown.
1745
    $this->assertText($comment1->subject, 'Comment found in block.');
1746
    $this->assertText($comment2->subject, 'Comment found in block.');
1747
    $this->assertText($comment3->comment, 'Comment found in block.');
1748
    $this->assertText($comment4->subject, 'Comment found in block.');
1749

    
1750
    // Test that links to comments work when comments are across pages.
1751
    $this->setCommentsPerPage(1);
1752
    $this->drupalGet('');
1753
    $this->clickLink($comment1->subject);
1754
    $this->assertText($comment1->subject, 'Comment link goes to correct page.');
1755
    $this->drupalGet('');
1756
    $this->clickLink($comment2->subject);
1757
    $this->assertText($comment2->subject, 'Comment link goes to correct page.');
1758
    $this->clickLink($comment4->subject);
1759
    $this->assertText($comment4->subject, 'Comment link goes to correct page.');
1760
    // Check that when viewing a comment page from a link to the comment, that
1761
    // rel="canonical" is added to the head of the document.
1762
    $this->assertRaw('<link rel="canonical"', 'Canonical URL was found in the HTML head');
1763
  }
1764
}
1765

    
1766
/**
1767
 * Unit tests for comment module integration with RSS feeds.
1768
 */
1769
class CommentRSSUnitTest extends CommentHelperCase {
1770
  public static function getInfo() {
1771
    return array(
1772
      'name' => 'Comment RSS',
1773
      'description' => 'Test comments as part of an RSS feed.',
1774
      'group' => 'Comment',
1775
    );
1776
  }
1777

    
1778
  /**
1779
   * Test comments as part of an RSS feed.
1780
   */
1781
  function testCommentRSS() {
1782
    // Find comment in RSS feed.
1783
    $this->drupalLogin($this->web_user);
1784
    $comment = $this->postComment($this->node, $this->randomName(), $this->randomName());
1785
    $this->drupalGet('rss.xml');
1786
    $raw = '<comments>' . url('node/' . $this->node->nid, array('fragment' => 'comments', 'absolute' => TRUE)) . '</comments>';
1787
    $this->assertRaw($raw, 'Comments as part of RSS feed.');
1788

    
1789
    // Hide comments from RSS feed and check presence.
1790
    $this->node->comment = COMMENT_NODE_HIDDEN;
1791
    node_save($this->node);
1792
    $this->drupalGet('rss.xml');
1793
    $this->assertNoRaw($raw, 'Hidden comments is not a part of RSS feed.');
1794
  }
1795
}
1796

    
1797

    
1798
/**
1799
 * Test to make sure comment content is rebuilt.
1800
 */
1801
class CommentContentRebuild extends CommentHelperCase {
1802
  public static function getInfo() {
1803
    return array(
1804
      'name' => 'Comment Rebuild',
1805
      'description' => 'Test to make sure the comment content is rebuilt.',
1806
      'group' => 'Comment',
1807
    );
1808
  }
1809

    
1810
  /**
1811
   * Test to ensure that the comment's content array is rebuilt for every
1812
   * call to comment_view().
1813
   */
1814
  function testCommentRebuild() {
1815
    // Update the comment settings so preview isn't required.
1816
    $this->drupalLogin($this->admin_user);
1817
    $this->setCommentSubject(TRUE);
1818
    $this->setCommentPreview(DRUPAL_OPTIONAL);
1819
    $this->drupalLogout();
1820

    
1821
    // Log in as the web user and add the comment.
1822
    $this->drupalLogin($this->web_user);
1823
    $subject_text = $this->randomName();
1824
    $comment_text = $this->randomName();
1825
    $comment = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
1826
    $comment_loaded = comment_load($comment->id);
1827
    $this->assertTrue($this->commentExists($comment), 'Comment found.');
1828

    
1829
    // Add the property to the content array and then see if it still exists on build.
1830
    $comment_loaded->content['test_property'] = array('#value' => $this->randomString());
1831
    $built_content = comment_view($comment_loaded, $this->node);
1832

    
1833
    // This means that the content was rebuilt as the added test property no longer exists.
1834
    $this->assertFalse(isset($built_content['test_property']), 'Comment content was emptied before being built.');
1835
  }
1836
}
1837

    
1838
/**
1839
 * Test comment token replacement in strings.
1840
 */
1841
class CommentTokenReplaceTestCase extends CommentHelperCase {
1842
  public static function getInfo() {
1843
    return array(
1844
      'name' => 'Comment token replacement',
1845
      'description' => 'Generates text using placeholders for dummy content to check comment token replacement.',
1846
      'group' => 'Comment',
1847
    );
1848
  }
1849

    
1850
  /**
1851
   * Creates a comment, then tests the tokens generated from it.
1852
   */
1853
  function testCommentTokenReplacement() {
1854
    global $language;
1855
    $url_options = array(
1856
      'absolute' => TRUE,
1857
      'language' => $language,
1858
    );
1859

    
1860
    $this->drupalLogin($this->admin_user);
1861

    
1862
    // Set comment variables.
1863
    $this->setCommentSubject(TRUE);
1864

    
1865
    // Create a node and a comment.
1866
    $node = $this->drupalCreateNode(array('type' => 'article'));
1867
    $parent_comment = $this->postComment($node, $this->randomName(), $this->randomName(), TRUE);
1868

    
1869
    // Post a reply to the comment.
1870
    $this->drupalGet('comment/reply/' . $node->nid . '/' . $parent_comment->id);
1871
    $child_comment = $this->postComment(NULL, $this->randomName(), $this->randomName());
1872
    $comment = comment_load($child_comment->id);
1873
    $comment->homepage = 'http://example.org/';
1874

    
1875
    // Add HTML to ensure that sanitation of some fields tested directly.
1876
    $comment->subject = '<blink>Blinking Comment</blink>';
1877
    $instance = field_info_instance('comment', 'body', 'comment_body');
1878

    
1879
    // Generate and test sanitized tokens.
1880
    $tests = array();
1881
    $tests['[comment:cid]'] = $comment->cid;
1882
    $tests['[comment:hostname]'] = check_plain($comment->hostname);
1883
    $tests['[comment:name]'] = filter_xss($comment->name);
1884
    $tests['[comment:mail]'] = check_plain($this->admin_user->mail);
1885
    $tests['[comment:homepage]'] = check_url($comment->homepage);
1886
    $tests['[comment:title]'] = filter_xss($comment->subject);
1887
    $tests['[comment:body]'] = _text_sanitize($instance, LANGUAGE_NONE, $comment->comment_body[LANGUAGE_NONE][0], 'value');
1888
    $tests['[comment:url]'] = url('comment/' . $comment->cid, $url_options + array('fragment' => 'comment-' . $comment->cid));
1889
    $tests['[comment:edit-url]'] = url('comment/' . $comment->cid . '/edit', $url_options);
1890
    $tests['[comment:created:since]'] = format_interval(REQUEST_TIME - $comment->created, 2, $language->language);
1891
    $tests['[comment:changed:since]'] = format_interval(REQUEST_TIME - $comment->changed, 2, $language->language);
1892
    $tests['[comment:parent:cid]'] = $comment->pid;
1893
    $tests['[comment:parent:title]'] = check_plain($parent_comment->subject);
1894
    $tests['[comment:node:nid]'] = $comment->nid;
1895
    $tests['[comment:node:title]'] = check_plain($node->title);
1896
    $tests['[comment:author:uid]'] = $comment->uid;
1897
    $tests['[comment:author:name]'] = check_plain($this->admin_user->name);
1898

    
1899
    // Test to make sure that we generated something for each token.
1900
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
1901

    
1902
    foreach ($tests as $input => $expected) {
1903
      $output = token_replace($input, array('comment' => $comment), array('language' => $language));
1904
      $this->assertEqual($output, $expected, format_string('Sanitized comment token %token replaced.', array('%token' => $input)));
1905
    }
1906

    
1907
    // Generate and test unsanitized tokens.
1908
    $tests['[comment:hostname]'] = $comment->hostname;
1909
    $tests['[comment:name]'] = $comment->name;
1910
    $tests['[comment:mail]'] = $this->admin_user->mail;
1911
    $tests['[comment:homepage]'] = $comment->homepage;
1912
    $tests['[comment:title]'] = $comment->subject;
1913
    $tests['[comment:body]'] = $comment->comment_body[LANGUAGE_NONE][0]['value'];
1914
    $tests['[comment:parent:title]'] = $parent_comment->subject;
1915
    $tests['[comment:node:title]'] = $node->title;
1916
    $tests['[comment:author:name]'] = $this->admin_user->name;
1917

    
1918
    foreach ($tests as $input => $expected) {
1919
      $output = token_replace($input, array('comment' => $comment), array('language' => $language, 'sanitize' => FALSE));
1920
      $this->assertEqual($output, $expected, format_string('Unsanitized comment token %token replaced.', array('%token' => $input)));
1921
    }
1922

    
1923
    // Load node so comment_count gets computed.
1924
    $node = node_load($node->nid);
1925

    
1926
    // Generate comment tokens for the node (it has 2 comments, both new).
1927
    $tests = array();
1928
    $tests['[node:comment-count]'] = 2;
1929
    $tests['[node:comment-count-new]'] = 2;
1930

    
1931
    foreach ($tests as $input => $expected) {
1932
      $output = token_replace($input, array('node' => $node), array('language' => $language));
1933
      $this->assertEqual($output, $expected, format_string('Node comment token %token replaced.', array('%token' => $input)));
1934
    }
1935
  }
1936
}
1937

    
1938
/**
1939
 * Test actions provided by the comment module.
1940
 */
1941
class CommentActionsTestCase extends CommentHelperCase {
1942
  public static function getInfo() {
1943
    return array(
1944
      'name' => 'Comment actions',
1945
      'description' => 'Test actions provided by the comment module.',
1946
      'group' => 'Comment',
1947
    );
1948
  }
1949

    
1950
  /**
1951
   * Test comment publish and unpublish actions.
1952
   */
1953
  function testCommentPublishUnpublishActions() {
1954
    $this->drupalLogin($this->web_user);
1955
    $comment_text = $this->randomName();
1956
    $subject = $this->randomName();
1957
    $comment = $this->postComment($this->node, $comment_text, $subject);
1958
    $comment = comment_load($comment->id);
1959

    
1960
    // Unpublish a comment (direct form: doesn't actually save the comment).
1961
    comment_unpublish_action($comment);
1962
    $this->assertEqual($comment->status, COMMENT_NOT_PUBLISHED, 'Comment was unpublished');
1963
    $this->assertWatchdogMessage('Unpublished comment %subject.', array('%subject' => $subject), 'Found watchdog message');
1964
    $this->clearWatchdog();
1965

    
1966
    // Unpublish a comment (indirect form: modify the comment in the database).
1967
    comment_unpublish_action(NULL, array('cid' => $comment->cid));
1968
    $this->assertEqual(comment_load($comment->cid)->status, COMMENT_NOT_PUBLISHED, 'Comment was unpublished');
1969
    $this->assertWatchdogMessage('Unpublished comment %subject.', array('%subject' => $subject), 'Found watchdog message');
1970

    
1971
    // Publish a comment (direct form: doesn't actually save the comment).
1972
    comment_publish_action($comment);
1973
    $this->assertEqual($comment->status, COMMENT_PUBLISHED, 'Comment was published');
1974
    $this->assertWatchdogMessage('Published comment %subject.', array('%subject' => $subject), 'Found watchdog message');
1975
    $this->clearWatchdog();
1976

    
1977
    // Publish a comment (indirect form: modify the comment in the database).
1978
    comment_publish_action(NULL, array('cid' => $comment->cid));
1979
    $this->assertEqual(comment_load($comment->cid)->status, COMMENT_PUBLISHED, 'Comment was published');
1980
    $this->assertWatchdogMessage('Published comment %subject.', array('%subject' => $subject), 'Found watchdog message');
1981
    $this->clearWatchdog();
1982
  }
1983

    
1984
  /**
1985
   * Tests the unpublish comment by keyword action.
1986
   */
1987
  public function testCommentUnpublishByKeyword() {
1988
    $this->drupalLogin($this->admin_user);
1989
    $callback = 'comment_unpublish_by_keyword_action';
1990
    $hash = drupal_hash_base64($callback);
1991
    $comment_text = $keywords = $this->randomName();
1992
    $edit = array(
1993
      'actions_label' => $callback,
1994
      'keywords' => $keywords,
1995
    );
1996

    
1997
    $this->drupalPost("admin/config/system/actions/configure/$hash", $edit, t('Save'));
1998

    
1999
    $action = db_query("SELECT aid, type, callback, parameters, label FROM {actions} WHERE callback = :callback", array(':callback' => $callback))->fetchObject();
2000

    
2001
    $this->assertTrue($action, 'The action could be loaded.');
2002

    
2003
    $comment = $this->postComment($this->node, $comment_text, $this->randomName());
2004

    
2005
    // Load the full comment so that status is available.
2006
    $comment = comment_load($comment->id);
2007

    
2008
    $this->assertTrue($comment->status == COMMENT_PUBLISHED, 'The comment status was set to published.');
2009

    
2010
    comment_unpublish_by_keyword_action($comment, array('keywords' => array($keywords)));
2011

    
2012
    // We need to make sure that the comment has been saved with status
2013
    // unpublished.
2014
    $this->assertEqual(comment_load($comment->cid)->status, COMMENT_NOT_PUBLISHED, 'Comment was unpublished.');
2015
    $this->assertWatchdogMessage('Unpublished comment %subject.', array('%subject' => $comment->subject), 'Found watchdog message.');
2016
    $this->clearWatchdog();
2017
  }
2018

    
2019
  /**
2020
   * Verify that a watchdog message has been entered.
2021
   *
2022
   * @param $watchdog_message
2023
   *   The watchdog message.
2024
   * @param $variables
2025
   *   The array of variables passed to watchdog().
2026
   * @param $message
2027
   *   The assertion message.
2028
   */
2029
  function assertWatchdogMessage($watchdog_message, $variables, $message) {
2030
    $status = (bool) db_query_range("SELECT 1 FROM {watchdog} WHERE message = :message AND variables = :variables", 0, 1, array(':message' => $watchdog_message, ':variables' => serialize($variables)))->fetchField();
2031
    return $this->assert($status, format_string('@message', array('@message' => $message)));
2032
  }
2033

    
2034
  /**
2035
   * Helper function: clear the watchdog.
2036
   */
2037
  function clearWatchdog() {
2038
    db_truncate('watchdog')->execute();
2039
  }
2040
}
2041

    
2042
/**
2043
 * Test fields on comments.
2044
 */
2045
class CommentFieldsTest extends CommentHelperCase {
2046
  public static function getInfo() {
2047
    return array(
2048
      'name' => 'Comment fields',
2049
      'description' => 'Tests fields on comments.',
2050
      'group' => 'Comment',
2051
    );
2052
  }
2053

    
2054
  /**
2055
   * Tests that the default 'comment_body' field is correctly added.
2056
   */
2057
  function testCommentDefaultFields() {
2058
    // Do not make assumptions on default node types created by the test
2059
    // installation profile, and create our own.
2060
    $this->drupalCreateContentType(array('type' => 'test_node_type'));
2061

    
2062
    // Check that the 'comment_body' field is present on all comment bundles.
2063
    $instances = field_info_instances('comment');
2064
    foreach (node_type_get_types() as $type_name => $info) {
2065
      $this->assertTrue(isset($instances['comment_node_' . $type_name]['comment_body']), format_string('The comment_body field is present for comments on type @type', array('@type' => $type_name)));
2066

    
2067
      // Delete the instance along the way.
2068
      field_delete_instance($instances['comment_node_' . $type_name]['comment_body']);
2069
    }
2070

    
2071
    // Check that the 'comment_body' field is deleted.
2072
    $field = field_info_field('comment_body');
2073
    $this->assertTrue(empty($field), 'The comment_body field was deleted');
2074

    
2075
    // Create a new content type.
2076
    $type_name = 'test_node_type_2';
2077
    $this->drupalCreateContentType(array('type' => $type_name));
2078

    
2079
    // Check that the 'comment_body' field exists and has an instance on the
2080
    // new comment bundle.
2081
    $field = field_info_field('comment_body');
2082
    $this->assertTrue($field, 'The comment_body field exists');
2083
    $instances = field_info_instances('comment');
2084
    $this->assertTrue(isset($instances['comment_node_' . $type_name]['comment_body']), format_string('The comment_body field is present for comments on type @type', array('@type' => $type_name)));
2085
  }
2086

    
2087
  /**
2088
   * Test that comment module works when enabled after a content module.
2089
   */
2090
  function testCommentEnable() {
2091
    // Create a user to do module administration.
2092
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
2093
    $this->drupalLogin($this->admin_user);
2094

    
2095
    // Disable the comment module.
2096
    $edit = array();
2097
    $edit['modules[Core][comment][enable]'] = FALSE;
2098
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
2099
    $this->resetAll();
2100
    $this->assertFalse(module_exists('comment'), 'Comment module disabled.');
2101

    
2102
    // Enable core content type modules (blog, book, and poll).
2103
    $edit = array();
2104
    $edit['modules[Core][blog][enable]'] = 'blog';
2105
    $edit['modules[Core][book][enable]'] = 'book';
2106
    $edit['modules[Core][poll][enable]'] = 'poll';
2107
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
2108
    $this->resetAll();
2109

    
2110
    // Now enable the comment module.
2111
    $edit = array();
2112
    $edit['modules[Core][comment][enable]'] = 'comment';
2113
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
2114
    $this->resetAll();
2115
    $this->assertTrue(module_exists('comment'), 'Comment module enabled.');
2116

    
2117
    // Create nodes of each type.
2118
    $blog_node = $this->drupalCreateNode(array('type' => 'blog'));
2119
    $book_node = $this->drupalCreateNode(array('type' => 'book'));
2120
    $poll_node = $this->drupalCreateNode(array('type' => 'poll', 'active' => 1, 'runtime' => 0, 'choice' => array(array('chtext' => ''))));
2121

    
2122
    $this->drupalLogout();
2123

    
2124
    // Try to post a comment on each node. A failure will be triggered if the
2125
    // comment body is missing on one of these forms, due to postComment()
2126
    // asserting that the body is actually posted correctly.
2127
    $this->web_user = $this->drupalCreateUser(array('access content', 'access comments', 'post comments', 'skip comment approval'));
2128
    $this->drupalLogin($this->web_user);
2129
    $this->postComment($blog_node, $this->randomName(), $this->randomName());
2130
    $this->postComment($book_node, $this->randomName(), $this->randomName());
2131
    $this->postComment($poll_node, $this->randomName(), $this->randomName());
2132
  }
2133

    
2134
  /**
2135
   * Test that comment module works correctly with plain text format.
2136
   */
2137
  function testCommentFormat() {
2138
    // Disable text processing for comments.
2139
    $this->drupalLogin($this->admin_user);
2140
    $edit = array('instance[settings][text_processing]' => 0);
2141
    $this->drupalPost('admin/structure/types/manage/article/comment/fields/comment_body', $edit, t('Save settings'));
2142

    
2143
    // Post a comment without an explicit subject.
2144
    $this->drupalLogin($this->web_user);
2145
    $edit = array('comment_body[und][0][value]' => $this->randomName(8));
2146
    $this->drupalPost('node/' . $this->node->nid, $edit, t('Save'));
2147
  }
2148
}
2149

    
2150
/**
2151
 * Tests comment threading.
2152
 */
2153
class CommentThreadingTestCase extends CommentHelperCase {
2154
  public static function getInfo() {
2155
    return array(
2156
      'name' => 'Comment Threading',
2157
      'description' => 'Test to make sure the comment number increments properly.',
2158
      'group' => 'Comment',
2159
    );
2160
  }
2161

    
2162
  /**
2163
   * Tests the comment threading.
2164
   */
2165
  function testCommentThreading() {
2166
    $langcode = LANGUAGE_NONE;
2167
    // Set comments to have a subject with preview disabled.
2168
    $this->drupalLogin($this->admin_user);
2169
    $this->setCommentPreview(DRUPAL_DISABLED);
2170
    $this->setCommentForm(TRUE);
2171
    $this->setCommentSubject(TRUE);
2172
    $this->setCommentSettings('comment_default_mode', COMMENT_MODE_THREADED, 'Comment paging changed.');
2173
    $this->drupalLogout();
2174

    
2175
    // Create a node.
2176
    $this->drupalLogin($this->web_user);
2177
    $this->node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1, 'uid' => $this->web_user->uid));
2178

    
2179
    // Post comment #1.
2180
    $this->drupalLogin($this->web_user);
2181
    $subject_text = $this->randomName();
2182
    $comment_text = $this->randomName();
2183
    $comment = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
2184
    $comment_loaded = comment_load($comment->id);
2185
    $this->assertTrue($this->commentExists($comment), 'Comment #1. Comment found.');
2186
    $this->assertEqual($comment_loaded->thread, '01/');
2187

    
2188
    // Reply to comment #1 creating comment #2.
2189
    $this->drupalLogin($this->web_user);
2190
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
2191
    $reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
2192
    $reply_loaded = comment_load($reply->id);
2193
    $this->assertTrue($this->commentExists($reply, TRUE), 'Comment #2. Reply found.');
2194
    $this->assertEqual($reply_loaded->thread, '01.00/');
2195

    
2196
    // Reply to comment #2 creating comment #3.
2197
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $reply->id);
2198
    $reply = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
2199
    $reply_loaded = comment_load($reply->id);
2200
    $this->assertTrue($this->commentExists($reply, TRUE), 'Comment #3. Second reply found.');
2201
    $this->assertEqual($reply_loaded->thread, '01.00.00/');
2202

    
2203
    // Reply to comment #1 creating comment #4.
2204
    $this->drupalLogin($this->web_user);
2205
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
2206
    $reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
2207
    $reply_loaded = comment_load($reply->id);
2208
    $this->assertTrue($this->commentExists($comment), 'Comment #4. Third reply found.');
2209
    $this->assertEqual($reply_loaded->thread, '01.01/');
2210

    
2211
    // Post comment #2 overall comment #5.
2212
    $this->drupalLogin($this->web_user);
2213
    $subject_text = $this->randomName();
2214
    $comment_text = $this->randomName();
2215
    $comment = $this->postComment($this->node, $comment_text, $subject_text, TRUE);
2216
    $comment_loaded = comment_load($comment->id);
2217
    $this->assertTrue($this->commentExists($comment), 'Comment #5. Second comment found.');
2218
    $this->assertEqual($comment_loaded->thread, '02/');
2219

    
2220
    // Reply to comment #5 creating comment #6.
2221
    $this->drupalLogin($this->web_user);
2222
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
2223
    $reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
2224
    $reply_loaded = comment_load($reply->id);
2225
    $this->assertTrue($this->commentExists($reply, TRUE), 'Comment #6. Reply found.');
2226
    $this->assertEqual($reply_loaded->thread, '02.00/');
2227

    
2228
    // Reply to comment #6 creating comment #7.
2229
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $reply->id);
2230
    $reply = $this->postComment(NULL, $this->randomName(), $this->randomName(), TRUE);
2231
    $reply_loaded = comment_load($reply->id);
2232
    $this->assertTrue($this->commentExists($reply, TRUE), 'Comment #7. Second reply found.');
2233
    $this->assertEqual($reply_loaded->thread, '02.00.00/');
2234

    
2235
    // Reply to comment #5 creating comment #8.
2236
    $this->drupalLogin($this->web_user);
2237
    $this->drupalGet('comment/reply/' . $this->node->nid . '/' . $comment->id);
2238
    $reply = $this->postComment(NULL, $this->randomName(), '', TRUE);
2239
    $reply_loaded = comment_load($reply->id);
2240
    $this->assertTrue($this->commentExists($comment), 'Comment #8. Third reply found.');
2241
    $this->assertEqual($reply_loaded->thread, '02.01/');
2242
  }
2243
}
2244

    
2245
/**
2246
 * Tests that comments behave correctly when the node is changed.
2247
 */
2248
class CommentNodeChangesTestCase extends CommentHelperCase {
2249

    
2250
  public static function getInfo() {
2251
    return array(
2252
      'name' => 'Comment deletion on node changes',
2253
      'description' => 'Tests that comments behave correctly when the node is changed.',
2254
      'group' => 'Comment',
2255
    );
2256
  }
2257

    
2258
  /**
2259
   * Tests that comments are deleted with the node.
2260
   */
2261
  function testNodeDeletion() {
2262
    $this->drupalLogin($this->web_user);
2263
    $comment = $this->postComment($this->node, $this->randomName(), $this->randomName());
2264
    $this->assertTrue(comment_load($comment->id), 'The comment could be loaded.');
2265
    node_delete($this->node->nid);
2266
    $this->assertFalse(comment_load($comment->id), 'The comment could not be loaded after the node was deleted.');
2267
  }
2268
}
2269

    
2270
/**
2271
 * Tests uninstalling the comment module.
2272
 */
2273
class CommentUninstallTestCase extends CommentHelperCase {
2274

    
2275
  public static function getInfo() {
2276
    return array(
2277
      'name' => 'Comment module uninstallation',
2278
      'description' => 'Tests that the comments module can be properly uninstalled.',
2279
      'group' => 'Comment',
2280
    );
2281
  }
2282

    
2283
  function testCommentUninstall() {
2284
    $this->drupalLogin($this->super_user);
2285

    
2286
    // Disable comment module.
2287
    $edit['modules[Core][comment][enable]'] = FALSE;
2288
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
2289
    $this->assertText(t('The configuration options have been saved.'), 'Comment module was disabled.');
2290

    
2291
    // Uninstall comment module.
2292
    $edit = array('uninstall[comment]' => 'comment');
2293
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
2294
    $this->drupalPost(NULL, NULL, t('Uninstall'));
2295
    $this->assertText(t('The selected modules have been uninstalled.'), 'Comment module was uninstalled.');
2296

    
2297
    // Run cron and clear field cache so that comment fields and instances
2298
    // marked for deletion are actually removed.
2299
    $this->cronRun();
2300
    field_cache_clear();
2301

    
2302
    // Verify that comment fields have been removed.
2303
    $all_fields = array_keys(field_info_field_map());
2304
    $this->assertFalse(in_array('comment_body', $all_fields), 'Comment fields were removed by uninstall.');
2305

    
2306
    // Verify that comment field instances have been removed (or at least marked
2307
    // for deletion).
2308
    // N.B. field_read_instances does an INNER JOIN on field_config so if the
2309
    // comment_body row has been removed successfully from there no instances
2310
    // will be returned, but that does not guarantee that no rows are left over
2311
    // in the field_config_instance table.
2312
    $count = db_select('field_config_instance', 'fci')
2313
      ->condition('entity_type', 'comment')
2314
      ->condition('field_name', 'comment_body')
2315
      ->condition('deleted', 0)
2316
      ->countQuery()
2317
      ->execute()
2318
      ->fetchField();
2319
    $this->assertTrue($count == 0, 'Comment field instances were removed by uninstall.');
2320
  }
2321
}