TrackerTest.php 18.8 KB
Newer Older
1
2
<?php

3
namespace Drupal\Tests\tracker\Functional;
4

5
use Drupal\comment\CommentInterface;
6
use Drupal\comment\Tests\CommentTestTrait;
7
use Drupal\Core\Cache\Cache;
8
use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
9
use Drupal\Core\Session\AccountInterface;
10
use Drupal\field\Entity\FieldStorageConfig;
11
use Drupal\node\Entity\Node;
12
use Drupal\Tests\BrowserTestBase;
13
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
14

15
/**
16
17
18
 * Create and delete nodes and check for their display in the tracker listings.
 *
 * @group tracker
19
 */
20
class TrackerTest extends BrowserTestBase {
21

22
  use CommentTestTrait;
23
  use AssertPageCacheContextsAndTagsTrait;
24

25
26
27
28
29
  /**
   * Modules to enable.
   *
   * @var array
   */
30
  public static $modules = ['block', 'comment', 'tracker', 'history', 'node_test'];
31

32
33
34
  /**
   * The main user for testing.
   *
35
   * @var \Drupal\user\UserInterface
36
   */
37
  protected $user;
38
39
40
41

  /**
   * A second user that will 'create' comments and nodes.
   *
42
   * @var \Drupal\user\UserInterface
43
   */
44
  protected $otherUser;
45

46
  protected function setUp() {
47
    parent::setUp();
48

49
    $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
50

51
    $permissions = ['access comments', 'create page content', 'post comments', 'skip comment approval'];
52
    $this->user = $this->drupalCreateUser($permissions);
53
    $this->otherUser = $this->drupalCreateUser($permissions);
54
    $this->addDefaultCommentField('node', 'page');
55
    user_role_grant_permissions(AccountInterface::ANONYMOUS_ROLE, [
56
57
      'access content',
      'access user profiles',
58
    ]);
59
60
    $this->drupalPlaceBlock('local_tasks_block', ['id' => 'page_tabs_block']);
    $this->drupalPlaceBlock('local_actions_block', ['id' => 'page_actions_block']);
61
62
63
  }

  /**
64
   * Tests for the presence of nodes on the global tracker listing.
65
   */
66
  public function testTrackerAll() {
67
68
    $this->drupalLogin($this->user);

69
    $unpublished = $this->drupalCreateNode([
70
      'title' => $this->randomMachineName(8),
71
      'status' => 0,
72
73
    ]);
    $published = $this->drupalCreateNode([
74
      'title' => $this->randomMachineName(8),
75
      'status' => 1,
76
    ]);
77

78
    $this->drupalGet('activity');
79
80
    $this->assertNoText($unpublished->label(), 'Unpublished node does not show up in the tracker listing.');
    $this->assertText($published->label(), 'Published node shows up in the tracker listing.');
81
    $this->assertLink(t('My recent content'), 0, 'User tab shows up on the global tracker page.');
82

83
    // Assert cache contexts, specifically the pager and node access contexts.
84
    $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user.node_grants:view', 'user']);
85
86
    // Assert cache tags for the action/tabs blocks, visible node, and node list
    // cache tag.
87
    $expected_tags = Cache::mergeTags($published->getCacheTags(), $published->getOwner()->getCacheTags());
88
89
90
91
92
93
    // Because the 'user.permissions' cache context is being optimized away.
    $role_tags = [];
    foreach ($this->user->getRoles() as $rid) {
      $role_tags[] = "config:user.role.$rid";
    }
    $expected_tags = Cache::mergeTags($expected_tags, $role_tags);
94
95
    $block_tags = [
      'block_view',
96
      'local_task',
97
98
99
100
101
102
103
104
105
106
      'config:block.block.page_actions_block',
      'config:block.block.page_tabs_block',
      'config:block_list',
    ];
    $expected_tags = Cache::mergeTags($expected_tags, $block_tags);
    $additional_tags = [
      'node_list',
      'rendered',
    ];
    $expected_tags = Cache::mergeTags($expected_tags, $additional_tags);
107
    $this->assertCacheTags($expected_tags);
108

109
    // Delete a node and ensure it no longer appears on the tracker.
110
    $published->delete();
111
    $this->drupalGet('activity');
112
    $this->assertNoText($published->label(), 'Deleted node does not show up in the tracker listing.');
113
114
115
116
117
118
119
120
121
122
123
124
125
126

    // Test proper display of time on activity page when comments are disabled.
    // Disable comments.
    FieldStorageConfig::loadByName('node', 'comment')->delete();
    $node = $this->drupalCreateNode([
      // This title is required to trigger the custom changed time set in the
      // node_test module. This is needed in order to ensure a sufficiently
      // large 'time ago' interval that isn't numbered in seconds.
      'title' => 'testing_node_presave',
      'status' => 1,
    ]);

    $this->drupalGet('activity');
    $this->assertText($node->label(), 'Published node shows up in the tracker listing.');
127
    $this->assertText(\Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime()), 'The changed time was displayed on the tracker listing.');
128
129
130
  }

  /**
131
   * Tests for the presence of nodes on a user's tracker listing.
132
   */
133
  public function testTrackerUser() {
134
135
    $this->drupalLogin($this->user);

136
    $unpublished = $this->drupalCreateNode([
137
      'title' => $this->randomMachineName(8),
138
      'uid' => $this->user->id(),
139
      'status' => 0,
140
141
    ]);
    $my_published = $this->drupalCreateNode([
142
      'title' => $this->randomMachineName(8),
143
      'uid' => $this->user->id(),
144
      'status' => 1,
145
146
    ]);
    $other_published_no_comment = $this->drupalCreateNode([
147
      'title' => $this->randomMachineName(8),
148
      'uid' => $this->otherUser->id(),
149
      'status' => 1,
150
151
    ]);
    $other_published_my_comment = $this->drupalCreateNode([
152
      'title' => $this->randomMachineName(8),
153
      'uid' => $this->otherUser->id(),
154
      'status' => 1,
155
156
    ]);
    $comment = [
157
158
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
159
    ];
160
    $this->drupalPostForm('comment/reply/node/' . $other_published_my_comment->id() . '/comment', $comment, t('Save'));
161

162
    $this->drupalGet('user/' . $this->user->id() . '/activity');
163
    $this->assertNoText($unpublished->label(), "Unpublished nodes do not show up in the user's tracker listing.");
164
    $this->assertText($my_published->label(), "Published nodes show up in the user's tracker listing.");
165
    $this->assertNoText($other_published_no_comment->label(), "Another user's nodes do not show up in the user's tracker listing.");
166
    $this->assertText($other_published_my_comment->label(), "Nodes that the user has commented on appear in the user's tracker listing.");
167

168
    // Assert cache contexts.
169
    $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user', 'user.node_grants:view']);
170
171
    // Assert cache tags for the visible nodes (including owners) and node list
    // cache tag.
172
173
174
    $expected_tags = Cache::mergeTags($my_published->getCacheTags(), $my_published->getOwner()->getCacheTags());
    $expected_tags = Cache::mergeTags($expected_tags, $other_published_my_comment->getCacheTags());
    $expected_tags = Cache::mergeTags($expected_tags, $other_published_my_comment->getOwner()->getCacheTags());
175
176
177
178
179
180
    // Because the 'user.permissions' cache context is being optimized away.
    $role_tags = [];
    foreach ($this->user->getRoles() as $rid) {
      $role_tags[] = "config:user.role.$rid";
    }
    $expected_tags = Cache::mergeTags($expected_tags, $role_tags);
181
182
    $block_tags = [
      'block_view',
183
      'local_task',
184
185
186
187
188
189
190
191
192
193
      'config:block.block.page_actions_block',
      'config:block.block.page_tabs_block',
      'config:block_list',
    ];
    $expected_tags = Cache::mergeTags($expected_tags, $block_tags);
    $additional_tags = [
      'node_list',
      'rendered',
    ];
    $expected_tags = Cache::mergeTags($expected_tags, $additional_tags);
194
195

    $this->assertCacheTags($expected_tags);
196
    $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user', 'user.node_grants:view']);
197

198
199
    $this->assertLink($my_published->label());
    $this->assertNoLink($unpublished->label());
200
    // Verify that title and tab title have been set correctly.
201
    $this->assertText('Activity', 'The user activity tab has the name "Activity".');
202
    $this->assertTitle(t('@name | @site', ['@name' => $this->user->getUsername(), '@site' => $this->config('system.site')->get('name')]), 'The user tracker page has the correct page title.');
203
204

    // Verify that unpublished comments are removed from the tracker.
205
    $admin_user = $this->drupalCreateUser(['post comments', 'administer comments', 'access user profiles']);
206
    $this->drupalLogin($admin_user);
207
    $this->drupalPostForm('comment/1/edit', ['status' => CommentInterface::NOT_PUBLISHED], t('Save'));
208
    $this->drupalGet('user/' . $this->user->id() . '/activity');
209
    $this->assertNoText($other_published_my_comment->label(), 'Unpublished comments are not counted on the tracker listing.');
210
211
212

    // Test escaping of title on user's tracker tab.
    \Drupal::service('module_installer')->install(['user_hooks_test']);
213
    Cache::invalidateTags(['rendered']);
214
215
216
217
218
    \Drupal::state()->set('user_hooks_test_user_format_name_alter', TRUE);
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertEscaped('<em>' . $this->user->id() . '</em>');

    \Drupal::state()->set('user_hooks_test_user_format_name_alter_safe', TRUE);
219
    Cache::invalidateTags(['rendered']);
220
221
222
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertNoEscaped('<em>' . $this->user->id() . '</em>');
    $this->assertRaw('<em>' . $this->user->id() . '</em>');
223
224
225
  }

  /**
226
   * Tests the metadata for the "new"/"updated" indicators.
227
   */
228
  public function testTrackerHistoryMetadata() {
229
230
    $this->drupalLogin($this->user);

231
    // Create a page node.
232
    $edit = [
233
      'title' => $this->randomMachineName(8),
234
    ];
235
    $node = $this->drupalCreateNode($edit);
236

237
    // Verify that the history metadata is present.
238
    $this->drupalGet('activity');
239
240
241
242
243
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->getChangedTime());
    $this->drupalGet('activity/' . $this->user->id());
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->getChangedTime());
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->getChangedTime());
244

245
246
247
    // Add a comment to the page, make sure it is created after the node by
    // sleeping for one second, to ensure the last comment timestamp is
    // different from before.
248
    $comment = [
249
250
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
251
    ];
252
    sleep(1);
253
    $this->drupalPostForm('comment/reply/node/' . $node->id() . '/comment', $comment, t('Save'));
254
255
256
257
    // Reload the node so that comment.module's hook_node_load()
    // implementation can set $node->last_comment_timestamp for the freshly
    // posted comment.
    $node = Node::load($node->id());
258

259
    // Verify that the history metadata is updated.
260
    $this->drupalGet('activity');
261
262
263
264
265
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->get('comment')->last_comment_timestamp);
    $this->drupalGet('activity/' . $this->user->id());
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->get('comment')->last_comment_timestamp);
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->get('comment')->last_comment_timestamp);
266

267
268
269
    // Log out, now verify that the metadata is still there, but the library is
    // not.
    $this->drupalLogout();
270
    $this->drupalGet('activity');
271
272
273
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->get('comment')->last_comment_timestamp, FALSE);
    $this->drupalGet('user/' . $this->user->id() . '/activity');
    $this->assertHistoryMetadata($node->id(), $node->getChangedTime(), $node->get('comment')->last_comment_timestamp, FALSE);
274
  }
275

276
277
278
  /**
   * Tests for ordering on a users tracker listing when comments are posted.
   */
279
  public function testTrackerOrderingNewComments() {
280
281
    $this->drupalLogin($this->user);

282
    $node_one = $this->drupalCreateNode([
283
      'title' => $this->randomMachineName(8),
284
    ]);
285

286
    $node_two = $this->drupalCreateNode([
287
      'title' => $this->randomMachineName(8),
288
    ]);
289

290
291
    // Now get otherUser to track these pieces of content.
    $this->drupalLogin($this->otherUser);
292
293

    // Add a comment to the first page.
294
    $comment = [
295
296
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
297
    ];
298
299
300
301
302
303
304
    $this->drupalPostForm('comment/reply/node/' . $node_one->id() . '/comment', $comment, t('Save'));

    // If the comment is posted in the same second as the last one then Drupal
    // can't tell the difference, so we wait one second here.
    sleep(1);

    // Add a comment to the second page.
305
    $comment = [
306
307
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
308
    ];
309
310
    $this->drupalPostForm('comment/reply/node/' . $node_two->id() . '/comment', $comment, t('Save'));

311
    // We should at this point have in our tracker for otherUser:
312
313
314
315
316
317
318
319
320
321
322
323
324
    // 1. node_two
    // 2. node_one
    // Because that's the reverse order of the posted comments.

    // Now we're going to post a comment to node_one which should jump it to the
    // top of the list.

    $this->drupalLogin($this->user);
    // If the comment is posted in the same second as the last one then Drupal
    // can't tell the difference, so we wait one second here.
    sleep(1);

    // Add a comment to the second page.
325
    $comment = [
326
327
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
328
    ];
329
330
    $this->drupalPostForm('comment/reply/node/' . $node_one->id() . '/comment', $comment, t('Save'));

331
332
333
    // Switch back to the otherUser and assert that the order has swapped.
    $this->drupalLogin($this->otherUser);
    $this->drupalGet('user/' . $this->otherUser->id() . '/activity');
334
335
336
337
338
339
340
341
    // This is a cheeky way of asserting that the nodes are in the right order
    // on the tracker page.
    // It's almost certainly too brittle.
    $pattern = '/' . preg_quote($node_one->getTitle()) . '.+' . preg_quote($node_two->getTitle()) . '/s';
    $this->verbose($pattern);
    $this->assertPattern($pattern, 'Most recently commented on node appears at the top of tracker');
  }

342
  /**
343
   * Tests that existing nodes are indexed by cron.
344
   */
345
  public function testTrackerCronIndexing() {
346
347
348
    $this->drupalLogin($this->user);

    // Create 3 nodes.
349
350
    $edits = [];
    $nodes = [];
351
    for ($i = 1; $i <= 3; $i++) {
352
      $edits[$i] = [
353
        'title' => $this->randomMachineName(),
354
      ];
355
356
357
358
      $nodes[$i] = $this->drupalCreateNode($edits[$i]);
    }

    // Add a comment to the last node as other user.
359
    $this->drupalLogin($this->otherUser);
360
    $comment = [
361
362
      'subject[0][value]' => $this->randomMachineName(),
      'comment_body[0][value]' => $this->randomMachineName(20),
363
    ];
364
    $this->drupalPostForm('comment/reply/node/' . $nodes[3]->id() . '/comment', $comment, t('Save'));
365

366
367
368
369
370
371
372
373
    // Create an unpublished node.
    $unpublished = $this->drupalCreateNode([
      'title' => $this->randomMachineName(8),
      'status' => 0,
    ]);

    // Start indexing backwards from node 4.
    \Drupal::state()->set('tracker.index_nid', 4);
374
375
376
377
378
379
380
381
382
383
384

    // Clear the current tracker tables and rebuild them.
    db_delete('tracker_node')
      ->execute();
    db_delete('tracker_user')
      ->execute();
    tracker_cron();

    $this->drupalLogin($this->user);

    // Fetch the user's tracker.
385
    $this->drupalGet('activity/' . $this->user->id());
386
387
388

    // Assert that all node titles are displayed.
    foreach ($nodes as $i => $node) {
389
      $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', ['@i' => $i]));
390
391
392
    }

    // Fetch the site-wide tracker.
393
    $this->drupalGet('activity');
394
395
396

    // Assert that all node titles are displayed.
    foreach ($nodes as $i => $node) {
397
      $this->assertText($node->label(), format_string('Node @i is displayed on the tracker listing pages.', ['@i' => $i]));
398
399
400
401
    }
  }

  /**
402
   * Tests that publish/unpublish works at admin/content/node.
403
   */
404
  public function testTrackerAdminUnpublish() {
405
    \Drupal::service('module_installer')->install(['views']);
406
    \Drupal::service('router.builder')->rebuild();
407
    $admin_user = $this->drupalCreateUser(['access content overview', 'administer nodes', 'bypass node access']);
408
409
    $this->drupalLogin($admin_user);

410
    $node = $this->drupalCreateNode([
411
      'title' => $this->randomMachineName(),
412
    ]);
413
414

    // Assert that the node is displayed.
415
    $this->drupalGet('activity');
416
    $this->assertText($node->label(), 'A node is displayed on the tracker listing pages.');
417
418

    // Unpublish the node and ensure that it's no longer displayed.
419
    $edit = [
420
      'action' => 'node_unpublish_action',
421
      'node_bulk_form[0]' => $node->id(),
422
    ];
423
    $this->drupalPostForm('admin/content', $edit, t('Apply to selected items'));
424

425
    $this->drupalGet('activity');
426
    $this->assertText(t('No content available.'), 'A node is displayed on the tracker listing pages.');
427
  }
428
429
430
431
432
433
434
435
436
437

  /**
   * Passes if the appropriate history metadata exists.
   *
   * Verify the data-history-node-id, data-history-node-timestamp and
   * data-history-node-last-comment-timestamp attributes, which are used by the
   * drupal.tracker-history library to add the appropriate "new" and "updated"
   * indicators, as well as the "x new" replies link to the tracker.
   * We do this in JavaScript to prevent breaking the render cache.
   *
438
   * @param int $node_id
439
   *   A node ID, that must exist as a data-history-node-id attribute
440
   * @param int $node_timestamp
441
442
   *   A node timestamp, that must exist as a data-history-node-timestamp
   *   attribute.
443
   * @param int $node_last_comment_timestamp
444
445
446
447
448
   *   A node's last comment timestamp, that must exist as a
   *   data-history-node-last-comment-timestamp attribute.
   * @param bool $library_is_present
   *   Whether the drupal.tracker-history library should be present or not.
   */
449
  public function assertHistoryMetadata($node_id, $node_timestamp, $node_last_comment_timestamp, $library_is_present = TRUE) {
450
451
452
453
454
455
    $settings = $this->getDrupalSettings();
    $this->assertIdentical($library_is_present, isset($settings['ajaxPageState']) && in_array('tracker/history', explode(',', $settings['ajaxPageState']['libraries'])), 'drupal.tracker-history library is present.');
    $this->assertIdentical(1, count($this->xpath('//table/tbody/tr/td[@data-history-node-id="' . $node_id . '" and @data-history-node-timestamp="' . $node_timestamp . '"]')), 'Tracker table cell contains the data-history-node-id and data-history-node-timestamp attributes for the node.');
    $this->assertIdentical(1, count($this->xpath('//table/tbody/tr/td[@data-history-node-last-comment-timestamp="' . $node_last_comment_timestamp . '"]')), 'Tracker table cell contains the data-history-node-last-comment-timestamp attribute for the node.');
  }

456
}