Projet

Général

Profil

Paste
Télécharger (112 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / node / node.test @ b4adf10d

1 85ad3d82 Assos Assos
<?php
2
3
/**
4
 * @file
5
 * Tests for node.module.
6
 */
7
8
/**
9
 * Defines a base class for testing the Node module.
10
 */
11
class NodeWebTestCase extends DrupalWebTestCase {
12
  function setUp() {
13
    $modules = func_get_args();
14
    if (isset($modules[0]) && is_array($modules[0])) {
15
      $modules = $modules[0];
16
    }
17
    $modules[] = 'node';
18
    parent::setUp($modules);
19
20
    // Create Basic page and Article node types.
21
    if ($this->profile != 'standard') {
22
      $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
23
      $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
24
    }
25
  }
26
}
27
28
/**
29
 * Test the node_load_multiple() function.
30
 */
31
class NodeLoadMultipleTestCase extends DrupalWebTestCase {
32
33
  public static function getInfo() {
34
    return array(
35
      'name' => 'Load multiple nodes',
36
      'description' => 'Test the loading of multiple nodes.',
37
      'group' => 'Node',
38
    );
39
  }
40
41
  function setUp() {
42
    parent::setUp();
43
    $web_user = $this->drupalCreateUser(array('create article content', 'create page content'));
44
    $this->drupalLogin($web_user);
45
  }
46
47
  /**
48
   * Create four nodes and ensure they're loaded correctly.
49
   */
50
  function testNodeMultipleLoad() {
51
    $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
52
    $node2 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
53
    $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 0));
54
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0));
55
56
    // Confirm that promoted nodes appear in the default node listing.
57
    $this->drupalGet('node');
58
    $this->assertText($node1->title, 'Node title appears on the default listing.');
59
    $this->assertText($node2->title, 'Node title appears on the default listing.');
60
    $this->assertNoText($node3->title, 'Node title does not appear in the default listing.');
61
    $this->assertNoText($node4->title, 'Node title does not appear in the default listing.');
62
63
    // Load nodes with only a condition. Nodes 3 and 4 will be loaded.
64
    $nodes = node_load_multiple(NULL, array('promote' => 0));
65
    $this->assertEqual($node3->title, $nodes[$node3->nid]->title, 'Node was loaded.');
66
    $this->assertEqual($node4->title, $nodes[$node4->nid]->title, 'Node was loaded.');
67
    $count = count($nodes);
68
    $this->assertTrue($count == 2, format_string('@count nodes loaded.', array('@count' => $count)));
69
70
    // Load nodes by nid. Nodes 1, 2 and 4 will be loaded.
71
    $nodes = node_load_multiple(array(1, 2, 4));
72
    $count = count($nodes);
73
    $this->assertTrue(count($nodes) == 3, format_string('@count nodes loaded', array('@count' => $count)));
74
    $this->assertTrue(isset($nodes[$node1->nid]), 'Node is correctly keyed in the array');
75
    $this->assertTrue(isset($nodes[$node2->nid]), 'Node is correctly keyed in the array');
76
    $this->assertTrue(isset($nodes[$node4->nid]), 'Node is correctly keyed in the array');
77
    foreach ($nodes as $node) {
78
      $this->assertTrue(is_object($node), 'Node is an object');
79
    }
80
81
    // Load nodes by nid, where type = article. Nodes 1, 2 and 3 will be loaded.
82
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article'));
83
    $count = count($nodes);
84
    $this->assertTrue($count == 3, format_string('@count nodes loaded', array('@count' => $count)));
85
    $this->assertEqual($nodes[$node1->nid]->title, $node1->title, 'Node successfully loaded.');
86
    $this->assertEqual($nodes[$node2->nid]->title, $node2->title, 'Node successfully loaded.');
87
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, 'Node successfully loaded.');
88
    $this->assertFalse(isset($nodes[$node4->nid]));
89
90
    // Now that all nodes have been loaded into the static cache, ensure that
91
    // they are loaded correctly again when a condition is passed.
92
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article'));
93
    $count = count($nodes);
94
    $this->assertTrue($count == 3, format_string('@count nodes loaded.', array('@count' => $count)));
95
    $this->assertEqual($nodes[$node1->nid]->title, $node1->title, 'Node successfully loaded');
96
    $this->assertEqual($nodes[$node2->nid]->title, $node2->title, 'Node successfully loaded');
97
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, 'Node successfully loaded');
98
    $this->assertFalse(isset($nodes[$node4->nid]), 'Node was not loaded');
99
100
    // Load nodes by nid, where type = article and promote = 0.
101
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article', 'promote' => 0));
102
    $count = count($nodes);
103
    $this->assertTrue($count == 1, format_string('@count node loaded', array('@count' => $count)));
104
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, 'Node successfully loaded.');
105
  }
106
}
107
108
/**
109
 * Tests for the hooks invoked during node_load().
110
 */
111
class NodeLoadHooksTestCase extends DrupalWebTestCase {
112
  public static function getInfo() {
113
    return array(
114
      'name' => 'Node load hooks',
115
      'description' => 'Test the hooks invoked when a node is being loaded.',
116
      'group' => 'Node',
117
    );
118
  }
119
120
  function setUp() {
121
    parent::setUp('node_test');
122
  }
123
124
  /**
125
   * Test that hook_node_load() is invoked correctly.
126
   */
127
  function testHookNodeLoad() {
128
    // Create some sample articles and pages.
129
    $node1 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_PUBLISHED));
130
    $node2 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_PUBLISHED));
131
    $node3 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_NOT_PUBLISHED));
132
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'status' => NODE_NOT_PUBLISHED));
133
134
    // Check that when a set of nodes that only contains articles is loaded,
135
    // the properties added to the node by node_test_load_node() correctly
136
    // reflect the expected values.
137
    $nodes = node_load_multiple(array(), array('status' => NODE_PUBLISHED));
138
    $loaded_node = end($nodes);
139
    $this->assertEqual($loaded_node->node_test_loaded_nids, array($node1->nid, $node2->nid), 'hook_node_load() received the correct list of node IDs the first time it was called.');
140
    $this->assertEqual($loaded_node->node_test_loaded_types, array('article'), 'hook_node_load() received the correct list of node types the first time it was called.');
141
142
    // Now, as part of the same page request, load a set of nodes that contain
143
    // both articles and pages, and make sure the parameters passed to
144
    // node_test_node_load() are correctly updated.
145
    $nodes = node_load_multiple(array(), array('status' => NODE_NOT_PUBLISHED));
146
    $loaded_node = end($nodes);
147
    $this->assertEqual($loaded_node->node_test_loaded_nids, array($node3->nid, $node4->nid), 'hook_node_load() received the correct list of node IDs the second time it was called.');
148
    $this->assertEqual($loaded_node->node_test_loaded_types, array('article', 'page'), 'hook_node_load() received the correct list of node types the second time it was called.');
149
  }
150
}
151
152
/**
153
 * Tests the node revision functionality.
154
 */
155
class NodeRevisionsTestCase extends DrupalWebTestCase {
156
157
  /**
158
   * Nodes used by the test.
159
   *
160
   * @var array
161
   */
162
  protected $nodes;
163
164
  /**
165
   * The revision messages for node revisions created in the test.
166
   *
167
   * @var array
168
   */
169
  protected $logs;
170
171
  public static function getInfo() {
172
    return array(
173
      'name' => 'Node revisions',
174
      'description' => 'Create a node with revisions and test viewing, saving, reverting, and deleting revisions.',
175
      'group' => 'Node',
176
    );
177
  }
178
179
  function setUp() {
180
    parent::setUp();
181
182
    // Create and login user.
183
    $web_user = $this->drupalCreateUser(array('view revisions', 'revert revisions', 'edit any page content',
184
                                               'delete revisions', 'delete any page content'));
185
    $this->drupalLogin($web_user);
186
187
    // Create initial node.
188
    $node = $this->drupalCreateNode();
189
    $settings = get_object_vars($node);
190
    $settings['revision'] = 1;
191
192
    $nodes = array();
193
    $logs = array();
194
195
    // Get original node.
196
    $nodes[] = $node;
197
198
    // Create three revisions.
199
    $revision_count = 3;
200
    for ($i = 0; $i < $revision_count; $i++) {
201
      $logs[] = $settings['log'] = $this->randomName(32);
202
203
      // Create revision with random title and body and update variables.
204
      $this->drupalCreateNode($settings);
205
      $node = node_load($node->nid); // Make sure we get revision information.
206
      $settings = get_object_vars($node);
207
208
      $nodes[] = $node;
209
    }
210
211
    $this->nodes = $nodes;
212
    $this->logs = $logs;
213
  }
214
215
  /**
216
   * Checks node revision related operations.
217
   */
218
  function testRevisions() {
219
    $nodes = $this->nodes;
220
    $logs = $this->logs;
221
222
    // Get last node for simple checks.
223
    $node = $nodes[3];
224
225
    // Confirm the correct revision text appears on "view revisions" page.
226
    $this->drupalGet("node/$node->nid/revisions/$node->vid/view");
227
    $this->assertText($node->body[LANGUAGE_NONE][0]['value'], 'Correct text displays for version.');
228
229
    // Confirm the correct log message appears on "revisions overview" page.
230
    $this->drupalGet("node/$node->nid/revisions");
231
    foreach ($logs as $log) {
232
      $this->assertText($log, 'Log message found.');
233
    }
234
235
    // Confirm that revisions revert properly.
236
    $this->drupalPost("node/$node->nid/revisions/{$nodes[1]->vid}/revert", array(), t('Revert'));
237
    $this->assertRaw(t('@type %title has been reverted back to the revision from %revision-date.',
238
                        array('@type' => 'Basic page', '%title' => $nodes[1]->title,
239
                              '%revision-date' => format_date($nodes[1]->revision_timestamp))), 'Revision reverted.');
240
    $reverted_node = node_load($node->nid);
241
    $this->assertTrue(($nodes[1]->body[LANGUAGE_NONE][0]['value'] == $reverted_node->body[LANGUAGE_NONE][0]['value']), 'Node reverted correctly.');
242
243
    // Confirm revisions delete properly.
244
    $this->drupalPost("node/$node->nid/revisions/{$nodes[1]->vid}/delete", array(), t('Delete'));
245
    $this->assertRaw(t('Revision from %revision-date of @type %title has been deleted.',
246
                        array('%revision-date' => format_date($nodes[1]->revision_timestamp),
247
                              '@type' => 'Basic page', '%title' => $nodes[1]->title)), 'Revision deleted.');
248
    $this->assertTrue(db_query('SELECT COUNT(vid) FROM {node_revision} WHERE nid = :nid and vid = :vid', array(':nid' => $node->nid, ':vid' => $nodes[1]->vid))->fetchField() == 0, 'Revision not found.');
249
  }
250
251
  /**
252
   * Checks that revisions are correctly saved without log messages.
253
   */
254
  function testNodeRevisionWithoutLogMessage() {
255
    // Create a node with an initial log message.
256
    $log = $this->randomName(10);
257
    $node = $this->drupalCreateNode(array('log' => $log));
258
259
    // Save over the same revision and explicitly provide an empty log message
260
    // (for example, to mimic the case of a node form submitted with no text in
261
    // the "log message" field), and check that the original log message is
262
    // preserved.
263
    $new_title = $this->randomName(10) . 'testNodeRevisionWithoutLogMessage1';
264
    $updated_node = (object) array(
265
      'nid' => $node->nid,
266
      'vid' => $node->vid,
267
      'uid' => $node->uid,
268
      'type' => $node->type,
269
      'title' => $new_title,
270
      'log' => '',
271
    );
272
    node_save($updated_node);
273
    $this->drupalGet('node/' . $node->nid);
274
    $this->assertText($new_title, 'New node title appears on the page.');
275
    $node_revision = node_load($node->nid, NULL, TRUE);
276
    $this->assertEqual($node_revision->log, $log, 'After an existing node revision is re-saved without a log message, the original log message is preserved.');
277
278
    // Create another node with an initial log message.
279
    $node = $this->drupalCreateNode(array('log' => $log));
280
281
    // Save a new node revision without providing a log message, and check that
282
    // this revision has an empty log message.
283
    $new_title = $this->randomName(10) . 'testNodeRevisionWithoutLogMessage2';
284
    $updated_node = (object) array(
285
      'nid' => $node->nid,
286
      'vid' => $node->vid,
287
      'uid' => $node->uid,
288
      'type' => $node->type,
289
      'title' => $new_title,
290
      'revision' => 1,
291
    );
292
    node_save($updated_node);
293
    $this->drupalGet('node/' . $node->nid);
294
    $this->assertText($new_title, 'New node title appears on the page.');
295
    $node_revision = node_load($node->nid, NULL, TRUE);
296
    $this->assertTrue(empty($node_revision->log), 'After a new node revision is saved with an empty log message, the log message for the node is empty.');
297
  }
298
}
299
300
/**
301
 * Tests the node edit functionality.
302
 */
303
class PageEditTestCase extends DrupalWebTestCase {
304
305
  /**
306
   * A user with permission to create and edit own page content.
307
   *
308
   * @var object
309
   */
310
  protected $web_user;
311
312
  /**
313
   * A user with permission to bypass node access and administer nodes.
314
   *
315
   * @var object
316
   */
317
  protected $admin_user;
318
319
  public static function getInfo() {
320
    return array(
321
      'name' => 'Node edit',
322
      'description' => 'Create a node and test node edit functionality.',
323
      'group' => 'Node',
324
    );
325
  }
326
327
  function setUp() {
328
    parent::setUp();
329
330
    $this->web_user = $this->drupalCreateUser(array('edit own page content', 'create page content'));
331
    $this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes'));
332
  }
333
334
  /**
335
   * Checks node edit functionality.
336
   */
337
  function testPageEdit() {
338
    $this->drupalLogin($this->web_user);
339
340
    $langcode = LANGUAGE_NONE;
341
    $title_key = "title";
342
    $body_key = "body[$langcode][0][value]";
343
    // Create node to edit.
344
    $edit = array();
345
    $edit[$title_key] = $this->randomName(8);
346
    $edit[$body_key] = $this->randomName(16);
347
    $this->drupalPost('node/add/page', $edit, t('Save'));
348
349
    // Check that the node exists in the database.
350
    $node = $this->drupalGetNodeByTitle($edit[$title_key]);
351
    $this->assertTrue($node, 'Node found in database.');
352
353
    // Check that "edit" link points to correct page.
354
    $this->clickLink(t('Edit'));
355
    $edit_url = url("node/$node->nid/edit", array('absolute' => TRUE));
356
    $actual_url = $this->getURL();
357
    $this->assertEqual($edit_url, $actual_url, 'On edit page.');
358
359
    // Check that the title and body fields are displayed with the correct values.
360
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
361
    $link_text = t('!local-task-title!active', array('!local-task-title' => t('Edit'), '!active' => $active));
362
    $this->assertText(strip_tags($link_text), 0, 'Edit tab found and marked active.');
363
    $this->assertFieldByName($title_key, $edit[$title_key], 'Title field displayed.');
364
    $this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.');
365
366
    // Edit the content of the node.
367
    $edit = array();
368
    $edit[$title_key] = $this->randomName(8);
369
    $edit[$body_key] = $this->randomName(16);
370
    // Stay on the current page, without reloading.
371
    $this->drupalPost(NULL, $edit, t('Save'));
372
373
    // Check that the title and body fields are displayed with the updated values.
374
    $this->assertText($edit[$title_key], 'Title displayed.');
375
    $this->assertText($edit[$body_key], 'Body displayed.');
376
377
    // Login as a second administrator user.
378
    $second_web_user = $this->drupalCreateUser(array('administer nodes', 'edit any page content'));
379
    $this->drupalLogin($second_web_user);
380
    // Edit the same node, creating a new revision.
381
    $this->drupalGet("node/$node->nid/edit");
382
    $edit = array();
383
    $edit['title'] = $this->randomName(8);
384
    $edit[$body_key] = $this->randomName(16);
385
    $edit['revision'] = TRUE;
386
    $this->drupalPost(NULL, $edit, t('Save'));
387
388
    // Ensure that the node revision has been created.
389
    $revised_node = $this->drupalGetNodeByTitle($edit['title']);
390
    $this->assertNotIdentical($node->vid, $revised_node->vid, 'A new revision has been created.');
391
    // Ensure that the node author is preserved when it was not changed in the
392
    // edit form.
393
    $this->assertIdentical($node->uid, $revised_node->uid, 'The node author has been preserved.');
394
    // Ensure that the revision authors are different since the revisions were
395
    // made by different users.
396
    $first_node_version = node_load($node->nid, $node->vid);
397
    $second_node_version = node_load($node->nid, $revised_node->vid);
398
    $this->assertNotIdentical($first_node_version->revision_uid, $second_node_version->revision_uid, 'Each revision has a distinct user.');
399
  }
400
401
  /**
402
   * Tests changing a node's "authored by" field.
403
   */
404
  function testPageAuthoredBy() {
405
    $this->drupalLogin($this->admin_user);
406
407
    // Create node to edit.
408
    $langcode = LANGUAGE_NONE;
409
    $body_key = "body[$langcode][0][value]";
410
    $edit = array();
411
    $edit['title'] = $this->randomName(8);
412
    $edit[$body_key] = $this->randomName(16);
413
    $this->drupalPost('node/add/page', $edit, t('Save'));
414
415
    // Check that the node was authored by the currently logged in user.
416
    $node = $this->drupalGetNodeByTitle($edit['title']);
417
    $this->assertIdentical($node->uid, $this->admin_user->uid, 'Node authored by admin user.');
418
419
    // Try to change the 'authored by' field to an invalid user name.
420
    $edit = array(
421
      'name' => 'invalid-name',
422
    );
423
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
424
    $this->assertText('The username invalid-name does not exist.');
425
426
    // Change the authored by field to an empty string, which should assign
427
    // authorship to the anonymous user (uid 0).
428
    $edit['name'] = '';
429
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
430
    $node = node_load($node->nid, NULL, TRUE);
431
    $this->assertIdentical($node->uid, '0', 'Node authored by anonymous user.');
432
433
    // Change the authored by field to another user's name (that is not
434
    // logged in).
435
    $edit['name'] = $this->web_user->name;
436
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
437
    $node = node_load($node->nid, NULL, TRUE);
438
    $this->assertIdentical($node->uid, $this->web_user->uid, 'Node authored by normal user.');
439
440
    // Check that normal users cannot change the authored by information.
441
    $this->drupalLogin($this->web_user);
442
    $this->drupalGet('node/' . $node->nid . '/edit');
443
    $this->assertNoFieldByName('name');
444
  }
445
}
446
447
/**
448
 * Tests the node entity preview functionality.
449
 */
450
class PagePreviewTestCase extends DrupalWebTestCase {
451
  public static function getInfo() {
452
    return array(
453
      'name' => 'Node preview',
454
      'description' => 'Test node preview functionality.',
455
      'group' => 'Node',
456
    );
457
  }
458
459
  function setUp() {
460
    parent::setUp();
461
462
    $web_user = $this->drupalCreateUser(array('edit own page content', 'create page content'));
463
    $this->drupalLogin($web_user);
464
  }
465
466
  /**
467
   * Checks the node preview functionality.
468
   */
469
  function testPagePreview() {
470
    $langcode = LANGUAGE_NONE;
471
    $title_key = "title";
472
    $body_key = "body[$langcode][0][value]";
473
474
    // Fill in node creation form and preview node.
475
    $edit = array();
476
    $edit[$title_key] = $this->randomName(8);
477
    $edit[$body_key] = $this->randomName(16);
478
    $this->drupalPost('node/add/page', $edit, t('Preview'));
479
480
    // Check that the preview is displaying the title and body.
481
    $this->assertTitle(t('Preview | Drupal'), 'Basic page title is preview.');
482
    $this->assertText($edit[$title_key], 'Title displayed.');
483
    $this->assertText($edit[$body_key], 'Body displayed.');
484
485
    // Check that the title and body fields are displayed with the correct values.
486
    $this->assertFieldByName($title_key, $edit[$title_key], 'Title field displayed.');
487
    $this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.');
488
  }
489
490
  /**
491
   * Checks the node preview functionality, when using revisions.
492
   */
493
  function testPagePreviewWithRevisions() {
494
    $langcode = LANGUAGE_NONE;
495
    $title_key = "title";
496
    $body_key = "body[$langcode][0][value]";
497
    // Force revision on "Basic page" content.
498
    variable_set('node_options_page', array('status', 'revision'));
499
500
    // Fill in node creation form and preview node.
501
    $edit = array();
502
    $edit[$title_key] = $this->randomName(8);
503
    $edit[$body_key] = $this->randomName(16);
504
    $edit['log'] = $this->randomName(32);
505
    $this->drupalPost('node/add/page', $edit, t('Preview'));
506
507
    // Check that the preview is displaying the title and body.
508
    $this->assertTitle(t('Preview | Drupal'), 'Basic page title is preview.');
509
    $this->assertText($edit[$title_key], 'Title displayed.');
510
    $this->assertText($edit[$body_key], 'Body displayed.');
511
512
    // Check that the title and body fields are displayed with the correct values.
513
    $this->assertFieldByName($title_key, $edit[$title_key], 'Title field displayed.');
514
    $this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.');
515
516
    // Check that the log field has the correct value.
517
    $this->assertFieldByName('log', $edit['log'], 'Log field displayed.');
518
  }
519
}
520
521
/**
522
 * Tests creating and saving a node.
523
 */
524
class NodeCreationTestCase extends DrupalWebTestCase {
525
  public static function getInfo() {
526
    return array(
527
      'name' => 'Node creation',
528
      'description' => 'Create a node and test saving it.',
529
      'group' => 'Node',
530
    );
531
  }
532
533
  function setUp() {
534
    // Enable dummy module that implements hook_node_insert for exceptions.
535
    parent::setUp('node_test_exception');
536
537
    $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
538
    $this->drupalLogin($web_user);
539
  }
540
541
  /**
542
   * Creates a "Basic page" node and verifies its consistency in the database.
543
   */
544
  function testNodeCreation() {
545
    // Create a node.
546
    $edit = array();
547
    $langcode = LANGUAGE_NONE;
548
    $edit["title"] = $this->randomName(8);
549
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
550
    $this->drupalPost('node/add/page', $edit, t('Save'));
551
552
    // Check that the Basic page has been created.
553
    $this->assertRaw(t('!post %title has been created.', array('!post' => 'Basic page', '%title' => $edit["title"])), 'Basic page created.');
554
555
    // Check that the node exists in the database.
556
    $node = $this->drupalGetNodeByTitle($edit["title"]);
557
    $this->assertTrue($node, 'Node found in database.');
558
  }
559
560
  /**
561
   * Verifies that a transaction rolls back the failed creation.
562
   */
563
  function testFailedPageCreation() {
564
    // Create a node.
565
    $edit = array(
566
      'uid'      => $this->loggedInUser->uid,
567
      'name'     => $this->loggedInUser->name,
568
      'type'     => 'page',
569
      'language' => LANGUAGE_NONE,
570
      'title'    => 'testing_transaction_exception',
571
    );
572
573
    try {
574 4444412d Julien Enselme
      // An exception is generated by node_test_exception_node_insert() if the
575
      // title is 'testing_transaction_exception'.
576 85ad3d82 Assos Assos
      node_save((object) $edit);
577
      $this->fail(t('Expected exception has not been thrown.'));
578
    }
579
    catch (Exception $e) {
580
      $this->pass(t('Expected exception has been thrown.'));
581
    }
582
583
    if (Database::getConnection()->supportsTransactions()) {
584
      // Check that the node does not exist in the database.
585
      $node = $this->drupalGetNodeByTitle($edit['title']);
586
      $this->assertFalse($node, 'Transactions supported, and node not found in database.');
587
    }
588
    else {
589
      // Check that the node exists in the database.
590
      $node = $this->drupalGetNodeByTitle($edit['title']);
591
      $this->assertTrue($node, 'Transactions not supported, and node found in database.');
592
593
      // Check that the failed rollback was logged.
594
      $records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
595
      $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
596
    }
597
598
    // Check that the rollback error was logged.
599
    $records = db_query("SELECT wid FROM {watchdog} WHERE variables LIKE '%Test exception for rollback.%'")->fetchAll();
600
    $this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
601
  }
602
603
  /**
604
   * Create an unpublished node and confirm correct redirect behavior.
605
   */
606
  function testUnpublishedNodeCreation() {
607
    // Set "Basic page" content type to be unpublished by default.
608
    variable_set('node_options_page', array());
609
    // Set the front page to the default "node" page.
610
    variable_set('site_frontpage', 'node');
611
612
    // Create a node.
613
    $edit = array();
614
    $edit["title"] = $this->randomName(8);
615
    $edit["body[" . LANGUAGE_NONE . "][0][value]"] = $this->randomName(16);
616
    $this->drupalPost('node/add/page', $edit, t('Save'));
617
618
    // Check that the user was redirected to the home page.
619
    $this->assertText(t('Welcome to Drupal'), t('The user is redirected to the home page.'));
620
  }
621
}
622
623
/**
624
 * Tests the functionality of node entity edit permissions.
625
 */
626
class PageViewTestCase extends DrupalWebTestCase {
627
  public static function getInfo() {
628
    return array(
629
      'name' => 'Node edit permissions',
630
      'description' => 'Create a node and test edit permissions.',
631
      'group' => 'Node',
632
    );
633
  }
634
635
  /**
636
   * Tests an anonymous and unpermissioned user attempting to edit the node.
637
   */
638
  function testPageView() {
639
    // Create a node to view.
640
    $node = $this->drupalCreateNode();
641
    $this->assertTrue(node_load($node->nid), 'Node created.');
642
643
    // Try to edit with anonymous user.
644
    $html = $this->drupalGet("node/$node->nid/edit");
645
    $this->assertResponse(403);
646
647
    // Create a user without permission to edit node.
648
    $web_user = $this->drupalCreateUser(array('access content'));
649
    $this->drupalLogin($web_user);
650
651
    // Attempt to access edit page.
652
    $this->drupalGet("node/$node->nid/edit");
653
    $this->assertResponse(403);
654
655
    // Create user with permission to edit node.
656
    $web_user = $this->drupalCreateUser(array('bypass node access'));
657
    $this->drupalLogin($web_user);
658
659
    // Attempt to access edit page.
660
    $this->drupalGet("node/$node->nid/edit");
661
    $this->assertResponse(200);
662
  }
663
}
664
665
/**
666
 * Tests the summary length functionality.
667
 */
668
class SummaryLengthTestCase extends DrupalWebTestCase {
669
  public static function getInfo() {
670
    return array(
671
      'name' => 'Summary length',
672
      'description' => 'Test summary length.',
673
      'group' => 'Node',
674
    );
675
  }
676
677
  /**
678
   * Tests the node summary length functionality.
679
   */
680
  function testSummaryLength() {
681
    // Create a node to view.
682
    $settings = array(
683
      'body' => array(LANGUAGE_NONE => array(array('value' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vitae arcu at leo cursus laoreet. Curabitur dui tortor, adipiscing malesuada tempor in, bibendum ac diam. Cras non tellus a libero pellentesque condimentum. What is a Drupalism? Suspendisse ac lacus libero. Ut non est vel nisl faucibus interdum nec sed leo. Pellentesque sem risus, vulputate eu semper eget, auctor in libero. Ut fermentum est vitae metus convallis scelerisque. Phasellus pellentesque rhoncus tellus, eu dignissim purus posuere id. Quisque eu fringilla ligula. Morbi ullamcorper, lorem et mattis egestas, tortor neque pretium velit, eget eleifend odio turpis eu purus. Donec vitae metus quis leo pretium tincidunt a pulvinar sem. Morbi adipiscing laoreet mauris vel placerat. Nullam elementum, nisl sit amet scelerisque malesuada, dolor nunc hendrerit quam, eu ultrices erat est in orci. Curabitur feugiat egestas nisl sed accumsan.'))),
684
      'promote' => 1,
685
    );
686
    $node = $this->drupalCreateNode($settings);
687
    $this->assertTrue(node_load($node->nid), 'Node created.');
688
689
    // Create user with permission to view the node.
690
    $web_user = $this->drupalCreateUser(array('access content', 'administer content types'));
691
    $this->drupalLogin($web_user);
692
693
    // Attempt to access the front page.
694
    $this->drupalGet("node");
695
    // The node teaser when it has 600 characters in length
696
    $expected = 'What is a Drupalism?';
697
    $this->assertRaw($expected, 'Check that the summary is 600 characters in length', 'Node');
698
699
    // Change the teaser length for "Basic page" content type.
700
    $instance = field_info_instance('node', 'body', $node->type);
701
    $instance['display']['teaser']['settings']['trim_length'] = 200;
702
    field_update_instance($instance);
703
704
    // Attempt to access the front page again and check if the summary is now only 200 characters in length.
705
    $this->drupalGet("node");
706
    $this->assertNoRaw($expected, 'Check that the summary is not longer than 200 characters', 'Node');
707
  }
708
}
709
710
/**
711
 * Tests XSS functionality with a node entity.
712
 */
713
class NodeTitleXSSTestCase extends DrupalWebTestCase {
714
  public static function getInfo() {
715
    return array(
716
      'name' => 'Node title XSS filtering',
717
      'description' => 'Create a node with dangerous tags in its title and test that they are escaped.',
718
      'group' => 'Node',
719
    );
720
  }
721
722
  /**
723
   * Tests XSS functionality with a node entity.
724
   */
725
  function testNodeTitleXSS() {
726
    // Prepare a user to do the stuff.
727
    $web_user = $this->drupalCreateUser(array('create page content', 'edit any page content'));
728
    $this->drupalLogin($web_user);
729
730
    $xss = '<script>alert("xss")</script>';
731
    $title = $xss . $this->randomName();
732
    $edit = array("title" => $title);
733
734
    $this->drupalPost('node/add/page', $edit, t('Preview'));
735
    $this->assertNoRaw($xss, 'Harmful tags are escaped when previewing a node.');
736
737
    $settings = array('title' => $title);
738
    $node = $this->drupalCreateNode($settings);
739
740
    $this->drupalGet('node/' . $node->nid);
741
    // assertTitle() decodes HTML-entities inside the <title> element.
742
    $this->assertTitle($edit["title"] . ' | Drupal', 'Title is diplayed when viewing a node.');
743
    $this->assertNoRaw($xss, 'Harmful tags are escaped when viewing a node.');
744
745
    $this->drupalGet('node/' . $node->nid . '/edit');
746
    $this->assertNoRaw($xss, 'Harmful tags are escaped when editing a node.');
747
  }
748
}
749
750
/**
751
 * Tests the availability of the syndicate block.
752
 */
753
class NodeBlockTestCase extends DrupalWebTestCase {
754
  public static function getInfo() {
755
    return array(
756
      'name' => 'Block availability',
757
      'description' => 'Check if the syndicate block is available.',
758
      'group' => 'Node',
759
    );
760
  }
761
762
  function setUp() {
763
    parent::setUp();
764
765
    // Create and login user
766
    $admin_user = $this->drupalCreateUser(array('administer blocks'));
767
    $this->drupalLogin($admin_user);
768
  }
769
770
  /**
771
   * Tests that the "Syndicate" block is shown when enabled.
772
   */
773
  function testSyndicateBlock() {
774
    // Set block title to confirm that the interface is available.
775
    $this->drupalPost('admin/structure/block/manage/node/syndicate/configure', array('title' => $this->randomName(8)), t('Save block'));
776
    $this->assertText(t('The block configuration has been saved.'), 'Block configuration set.');
777
778
    // Set the block to a region to confirm block is available.
779
    $edit = array();
780
    $edit['blocks[node_syndicate][region]'] = 'footer';
781
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
782
    $this->assertText(t('The block settings have been updated.'), 'Block successfully move to footer region.');
783
  }
784
}
785
786
/**
787
 * Checks that the post information displays when enabled for a content type.
788
 */
789
class NodePostSettingsTestCase extends DrupalWebTestCase {
790
  public static function getInfo() {
791
    return array(
792
      'name' => 'Node post information display',
793
      'description' => 'Check that the post information (submitted by Username on date) text displays appropriately.',
794
      'group' => 'Node',
795
    );
796
  }
797
798
  function setUp() {
799
    parent::setUp();
800
801
    $web_user = $this->drupalCreateUser(array('create page content', 'administer content types', 'access user profiles'));
802
    $this->drupalLogin($web_user);
803
  }
804
805
  /**
806
   * Confirms "Basic page" content type and post information is on a new node.
807
   */
808
  function testPagePostInfo() {
809
810
    // Set "Basic page" content type to display post information.
811
    $edit = array();
812
    $edit['node_submitted'] = TRUE;
813
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
814
815
    // Create a node.
816
    $edit = array();
817
    $langcode = LANGUAGE_NONE;
818
    $edit["title"] = $this->randomName(8);
819
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
820
    $this->drupalPost('node/add/page', $edit, t('Save'));
821
822
    // Check that the post information is displayed.
823
    $node = $this->drupalGetNodeByTitle($edit["title"]);
824
    $elements = $this->xpath('//div[contains(@class,:class)]', array(':class' => 'submitted'));
825
    $this->assertEqual(count($elements), 1, 'Post information is displayed.');
826
  }
827
828
  /**
829
   * Confirms absence of post information on a new node.
830
   */
831
  function testPageNotPostInfo() {
832
833
    // Set "Basic page" content type to display post information.
834
    $edit = array();
835
    $edit['node_submitted'] = FALSE;
836
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
837
838
    // Create a node.
839
    $edit = array();
840
    $langcode = LANGUAGE_NONE;
841
    $edit["title"] = $this->randomName(8);
842
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
843
    $this->drupalPost('node/add/page', $edit, t('Save'));
844
845
    // Check that the post information is displayed.
846
    $node = $this->drupalGetNodeByTitle($edit["title"]);
847
    $this->assertNoRaw('<span class="submitted">', 'Post information is not displayed.');
848
  }
849
}
850
851
/**
852
 * Ensures that data added to nodes by other modules appears in RSS feeds.
853
 *
854
 * Create a node, enable the node_test module to ensure that extra data is
855
 * added to the node->content array, then verify that the data appears on the
856
 * sitewide RSS feed at rss.xml.
857
 */
858
class NodeRSSContentTestCase extends DrupalWebTestCase {
859
  public static function getInfo() {
860
    return array(
861
      'name' => 'Node RSS Content',
862
      'description' => 'Ensure that data added to nodes by other modules appears in RSS feeds.',
863
      'group' => 'Node',
864
    );
865
  }
866
867
  function setUp() {
868
    // Enable dummy module that implements hook_node_view.
869
    parent::setUp('node_test');
870
871
    // Use bypass node access permission here, because the test class uses
872
    // hook_grants_alter() to deny access to everyone on node_access
873
    // queries.
874
    $user = $this->drupalCreateUser(array('bypass node access', 'access content', 'create article content'));
875
    $this->drupalLogin($user);
876
  }
877
878
  /**
879
   * Ensures that a new node includes the custom data when added to an RSS feed.
880
   */
881
  function testNodeRSSContent() {
882
    // Create a node.
883
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
884
885
    $this->drupalGet('rss.xml');
886
887
    // Check that content added in 'rss' view mode appear in RSS feed.
888
    $rss_only_content = t('Extra data that should appear only in the RSS feed for node !nid.', array('!nid' => $node->nid));
889
    $this->assertText($rss_only_content, 'Node content designated for RSS appear in RSS feed.');
890
891
    // Check that content added in view modes other than 'rss' doesn't
892
    // appear in RSS feed.
893
    $non_rss_content = t('Extra data that should appear everywhere except the RSS feed for node !nid.', array('!nid' => $node->nid));
894
    $this->assertNoText($non_rss_content, 'Node content not designed for RSS doesn\'t appear in RSS feed.');
895
896
    // Check that extra RSS elements and namespaces are added to RSS feed.
897
    $test_element = array(
898
      'key' => 'testElement',
899
      'value' => t('Value of testElement RSS element for node !nid.', array('!nid' => $node->nid)),
900
    );
901
    $test_ns = 'xmlns:drupaltest="http://example.com/test-namespace"';
902
    $this->assertRaw(format_xml_elements(array($test_element)), 'Extra RSS elements appear in RSS feed.');
903
    $this->assertRaw($test_ns, 'Extra namespaces appear in RSS feed.');
904
905
    // Check that content added in 'rss' view mode doesn't appear when
906
    // viewing node.
907
    $this->drupalGet("node/$node->nid");
908
    $this->assertNoText($rss_only_content, 'Node content designed for RSS doesn\'t appear when viewing node.');
909
910
    // Check that the node feed page does not try to interpret additional path
911
    // components as arguments for node_feed() and returns default content.
912
    $this->drupalGet('rss.xml/' . $this->randomName() . '/' . $this->randomName());
913
    $this->assertText($rss_only_content, 'Ignore page arguments when delivering rss.xml.');
914
  }
915
}
916
917
/**
918
 * Tests basic node_access functionality.
919
 *
920
 * Note that hook_node_access_records() is covered in another test class.
921
 *
922
 * @todo Cover hook_node_access in a separate test class.
923
 */
924
class NodeAccessTestCase extends DrupalWebTestCase {
925
  public static function getInfo() {
926
    return array(
927
      'name' => 'Node access',
928
      'description' => 'Test node_access function',
929
      'group' => 'Node',
930
    );
931
  }
932
933
  /**
934
   * Asserts node_access() correctly grants or denies access.
935
   */
936
  function assertNodeAccess($ops, $node, $account) {
937
    foreach ($ops as $op => $result) {
938
      $msg = format_string("node_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
939
      $this->assertEqual($result, node_access($op, $node, $account), $msg);
940
    }
941
  }
942
943
  function setUp() {
944
    parent::setUp();
945
    // Clear permissions for authenticated users.
946
    db_delete('role_permission')
947
      ->condition('rid', DRUPAL_AUTHENTICATED_RID)
948
      ->execute();
949
  }
950
951
  /**
952
   * Runs basic tests for node_access function.
953
   */
954
  function testNodeAccess() {
955
    // Ensures user without 'access content' permission can do nothing.
956
    $web_user1 = $this->drupalCreateUser(array('create page content', 'edit any page content', 'delete any page content'));
957
    $node1 = $this->drupalCreateNode(array('type' => 'page'));
958
    $this->assertNodeAccess(array('create' => FALSE), 'page', $web_user1);
959
    $this->assertNodeAccess(array('view' => FALSE, 'update' => FALSE, 'delete' => FALSE), $node1, $web_user1);
960
961
    // Ensures user with 'bypass node access' permission can do everything.
962
    $web_user2 = $this->drupalCreateUser(array('bypass node access'));
963
    $node2 = $this->drupalCreateNode(array('type' => 'page'));
964
    $this->assertNodeAccess(array('create' => TRUE), 'page', $web_user2);
965
    $this->assertNodeAccess(array('view' => TRUE, 'update' => TRUE, 'delete' => TRUE), $node2, $web_user2);
966
967
    // User cannot 'view own unpublished content'.
968
    $web_user3 = $this->drupalCreateUser(array('access content'));
969
    $node3 = $this->drupalCreateNode(array('status' => 0, 'uid' => $web_user3->uid));
970
    $this->assertNodeAccess(array('view' => FALSE), $node3, $web_user3);
971
972
    // User cannot create content without permission.
973
    $this->assertNodeAccess(array('create' => FALSE), 'page', $web_user3);
974
975
    // User can 'view own unpublished content', but another user cannot.
976
    $web_user4 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
977
    $web_user5 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
978
    $node4 = $this->drupalCreateNode(array('status' => 0, 'uid' => $web_user4->uid));
979
    $this->assertNodeAccess(array('view' => TRUE, 'update' => FALSE), $node4, $web_user4);
980
    $this->assertNodeAccess(array('view' => FALSE), $node4, $web_user5);
981
982
    // Tests the default access provided for a published node.
983
    $node5 = $this->drupalCreateNode();
984
    $this->assertNodeAccess(array('view' => TRUE, 'update' => FALSE, 'delete' => FALSE), $node5, $web_user3);
985
  }
986
}
987
988
/**
989
 * Tests hook_node_access_records() functionality.
990
 */
991
class NodeAccessRecordsTestCase extends DrupalWebTestCase {
992
  public static function getInfo() {
993
    return array(
994
      'name' => 'Node access records',
995
      'description' => 'Test hook_node_access_records when acquiring grants.',
996
      'group' => 'Node',
997
    );
998
  }
999
1000
  function setUp() {
1001
    // Enable dummy module that implements hook_node_grants(),
1002
    // hook_node_access_records(), hook_node_grants_alter() and
1003
    // hook_node_access_records_alter().
1004
    parent::setUp('node_test');
1005
  }
1006
1007
  /**
1008
   * Creates a node and tests the creation of node access rules.
1009
   */
1010
  function testNodeAccessRecords() {
1011
    // Create an article node.
1012
    $node1 = $this->drupalCreateNode(array('type' => 'article'));
1013
    $this->assertTrue(node_load($node1->nid), 'Article node created.');
1014
1015
    // Check to see if grants added by node_test_node_access_records made it in.
1016
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node1->nid))->fetchAll();
1017
    $this->assertEqual(count($records), 1, 'Returned the correct number of rows.');
1018
    $this->assertEqual($records[0]->realm, 'test_article_realm', 'Grant with article_realm acquired for node without alteration.');
1019
    $this->assertEqual($records[0]->gid, 1, 'Grant with gid = 1 acquired for node without alteration.');
1020
1021
    // Create an unpromoted "Basic page" node.
1022
    $node2 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0));
1023
    $this->assertTrue(node_load($node2->nid), 'Unpromoted basic page node created.');
1024
1025
    // Check to see if grants added by node_test_node_access_records made it in.
1026
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node2->nid))->fetchAll();
1027
    $this->assertEqual(count($records), 1, 'Returned the correct number of rows.');
1028
    $this->assertEqual($records[0]->realm, 'test_page_realm', 'Grant with page_realm acquired for node without alteration.');
1029
    $this->assertEqual($records[0]->gid, 1, 'Grant with gid = 1 acquired for node without alteration.');
1030
1031
    // Create an unpromoted, unpublished "Basic page" node.
1032
    $node3 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0, 'status' => 0));
1033
    $this->assertTrue(node_load($node3->nid), 'Unpromoted, unpublished basic page node created.');
1034
1035
    // Check to see if grants added by node_test_node_access_records made it in.
1036
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node3->nid))->fetchAll();
1037
    $this->assertEqual(count($records), 1, 'Returned the correct number of rows.');
1038
    $this->assertEqual($records[0]->realm, 'test_page_realm', 'Grant with page_realm acquired for node without alteration.');
1039
    $this->assertEqual($records[0]->gid, 1, 'Grant with gid = 1 acquired for node without alteration.');
1040
1041
    // Create a promoted "Basic page" node.
1042
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1));
1043
    $this->assertTrue(node_load($node4->nid), 'Promoted basic page node created.');
1044
1045
    // Check to see if grant added by node_test_node_access_records was altered
1046
    // by node_test_node_access_records_alter.
1047
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node4->nid))->fetchAll();
1048
    $this->assertEqual(count($records), 1, 'Returned the correct number of rows.');
1049
    $this->assertEqual($records[0]->realm, 'test_alter_realm', 'Altered grant with alter_realm acquired for node.');
1050
    $this->assertEqual($records[0]->gid, 2, 'Altered grant with gid = 2 acquired for node.');
1051
1052
    // Check to see if we can alter grants with hook_node_grants_alter().
1053
    $operations = array('view', 'update', 'delete');
1054
    // Create a user that is allowed to access content.
1055
    $web_user = $this->drupalCreateUser(array('access content'));
1056
    foreach ($operations as $op) {
1057
      $grants = node_test_node_grants($op, $web_user);
1058
      $altered_grants = $grants;
1059
      drupal_alter('node_grants', $altered_grants, $web_user, $op);
1060
      $this->assertNotEqual($grants, $altered_grants, format_string('Altered the %op grant for a user.', array('%op' => $op)));
1061
    }
1062
1063
    // Check that core does not grant access to an unpublished node when an
1064
    // empty $grants array is returned.
1065
    $node6 = $this->drupalCreateNode(array('status' => 0, 'disable_node_access' => TRUE));
1066
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node6->nid))->fetchAll();
1067
    $this->assertEqual(count($records), 0, 'Returned no records for unpublished node.');
1068
  }
1069
}
1070
1071
/**
1072
 * Tests for Node Access with a non-node base table.
1073
 */
1074
class NodeAccessBaseTableTestCase extends DrupalWebTestCase {
1075
1076
  public static function getInfo() {
1077
    return array(
1078
      'name' => 'Node Access on any table',
1079
      'description' => 'Checks behavior of the node access subsystem if the base table is not node.',
1080
      'group' => 'Node',
1081
    );
1082
  }
1083
1084
  public function setUp() {
1085
    parent::setUp('node_access_test');
1086
    node_access_rebuild();
1087
    variable_set('node_access_test_private', TRUE);
1088
  }
1089
1090
  /**
1091
   * Tests the "private" node access functionality.
1092
   *
1093
   * - Create 2 users with "access content" and "create article" permissions.
1094
   * - Each user creates one private and one not private article.
1095
1096
   * - Test that each user can view the other user's non-private article.
1097
   * - Test that each user cannot view the other user's private article.
1098
   * - Test that each user finds only appropriate (non-private + own private)
1099
   *   in taxonomy listing.
1100
   * - Create another user with 'view any private content'.
1101
   * - Test that user 4 can view all content created above.
1102
   * - Test that user 4 can view all content on taxonomy listing.
1103
   */
1104
  function testNodeAccessBasic() {
1105
    $num_simple_users = 2;
1106
    $simple_users = array();
1107
1108
    // nodes keyed by uid and nid: $nodes[$uid][$nid] = $is_private;
1109
    $this->nodesByUser = array();
1110
    $titles = array(); // Titles keyed by nid
1111
    $private_nodes = array(); // Array of nids marked private.
1112
    for ($i = 0; $i < $num_simple_users; $i++) {
1113
      $simple_users[$i] = $this->drupalCreateUser(array('access content', 'create article content'));
1114
    }
1115
    foreach ($simple_users as $this->webUser) {
1116
      $this->drupalLogin($this->webUser);
1117
      foreach (array(0 => 'Public', 1 => 'Private') as $is_private => $type) {
1118
        $edit = array(
1119
          'title' => t('@private_public Article created by @user', array('@private_public' => $type, '@user' => $this->webUser->name)),
1120
        );
1121
        if ($is_private) {
1122
          $edit['private'] = TRUE;
1123
          $edit['body[und][0][value]'] = 'private node';
1124
          $edit['field_tags[und]'] = 'private';
1125
        }
1126
        else {
1127
          $edit['body[und][0][value]'] = 'public node';
1128
          $edit['field_tags[und]'] = 'public';
1129
        }
1130
1131
        $this->drupalPost('node/add/article', $edit, t('Save'));
1132
        $nid = db_query('SELECT nid FROM {node} WHERE title = :title', array(':title' => $edit['title']))->fetchField();
1133
        $private_status = db_query('SELECT private FROM {node_access_test} where nid = :nid', array(':nid' => $nid))->fetchField();
1134
        $this->assertTrue($is_private == $private_status, 'The private status of the node was properly set in the node_access_test table.');
1135
        if ($is_private) {
1136
          $private_nodes[] = $nid;
1137
        }
1138
        $titles[$nid] = $edit['title'];
1139
        $this->nodesByUser[$this->webUser->uid][$nid] = $is_private;
1140
      }
1141
    }
1142
    $this->publicTid = db_query('SELECT tid FROM {taxonomy_term_data} WHERE name = :name', array(':name' => 'public'))->fetchField();
1143
    $this->privateTid = db_query('SELECT tid FROM {taxonomy_term_data} WHERE name = :name', array(':name' => 'private'))->fetchField();
1144
    $this->assertTrue($this->publicTid, 'Public tid was found');
1145
    $this->assertTrue($this->privateTid, 'Private tid was found');
1146
    foreach ($simple_users as $this->webUser) {
1147
      $this->drupalLogin($this->webUser);
1148
      // Check own nodes to see that all are readable.
1149
      foreach ($this->nodesByUser as $uid => $data) {
1150
        foreach ($data as $nid => $is_private) {
1151
          $this->drupalGet('node/' . $nid);
1152
          if ($is_private) {
1153
            $should_be_visible = $uid == $this->webUser->uid;
1154
          }
1155
          else {
1156
            $should_be_visible = TRUE;
1157
          }
1158
          $this->assertResponse($should_be_visible ? 200 : 403, strtr('A %private node by user %uid is %visible for user %current_uid.', array(
1159
            '%private' => $is_private ? 'private' : 'public',
1160
            '%uid' => $uid,
1161
            '%visible' => $should_be_visible ? 'visible' : 'not visible',
1162
            '%current_uid' => $this->webUser->uid,
1163
          )));
1164
        }
1165
      }
1166
1167
      // Check to see that the correct nodes are shown on taxonomy/private
1168
      // and taxonomy/public.
1169
      $this->assertTaxonomyPage(FALSE);
1170
    }
1171
1172
    // Now test that a user with 'access any private content' can view content.
1173
    $access_user = $this->drupalCreateUser(array('access content', 'create article content', 'node test view', 'search content'));
1174
    $this->drupalLogin($access_user);
1175
1176
    foreach ($this->nodesByUser as $uid => $private_status) {
1177
      foreach ($private_status as $nid => $is_private) {
1178
        $this->drupalGet('node/' . $nid);
1179
        $this->assertResponse(200);
1180
      }
1181
    }
1182
1183
    // This user should be able to see all of the nodes on the relevant
1184
    // taxonomy pages.
1185
    $this->assertTaxonomyPage(TRUE);
1186
  }
1187
1188
  /**
1189
   * Checks taxonomy/term listings to ensure only accessible nodes are listed.
1190
   *
1191
   * @param $is_admin
1192
   *   A boolean indicating whether the current user is an administrator. If
1193
   *   TRUE, all nodes should be listed. If FALSE, only public nodes and the
1194
   *   user's own private nodes should be listed.
1195
   */
1196
  protected function assertTaxonomyPage($is_admin) {
1197
    foreach (array($this->publicTid, $this->privateTid) as $tid_is_private => $tid) {
1198
      $this->drupalGet("taxonomy/term/$tid");
1199
      $this->nids_visible = array();
1200
      foreach ($this->xpath("//a[text()='Read more']") as $link) {
1201
        $this->assertTrue(preg_match('|node/(\d+)$|', (string) $link['href'], $matches), 'Read more points to a node');
1202
        $this->nids_visible[$matches[1]] = TRUE;
1203
      }
1204
      foreach ($this->nodesByUser as $uid => $data) {
1205
        foreach ($data as $nid => $is_private) {
1206
          // Private nodes should be visible on the private term page,
1207
          // public nodes should be visible on the public term page.
1208
          $should_be_visible = $tid_is_private == $is_private;
1209
          // Non-administrators can only see their own nodes on the private
1210
          // term page.
1211
          if (!$is_admin && $tid_is_private) {
1212
            $should_be_visible = $should_be_visible && $uid == $this->webUser->uid;
1213
          }
1214
          $this->assertIdentical(isset($this->nids_visible[$nid]), $should_be_visible, strtr('A %private node by user %uid is %visible for user %current_uid on the %tid_is_private page.', array(
1215
            '%private' => $is_private ? 'private' : 'public',
1216
            '%uid' => $uid,
1217
            '%visible' => isset($this->nids_visible[$nid]) ? 'visible' : 'not visible',
1218
            '%current_uid' => $this->webUser->uid,
1219
            '%tid_is_private' => $tid_is_private ? 'private' : 'public',
1220
          )));
1221
        }
1222
      }
1223
    }
1224
  }
1225
}
1226
1227
/**
1228
 * Tests node save related functionality, including import-save.
1229
 */
1230
class NodeSaveTestCase extends DrupalWebTestCase {
1231
1232
  public static function getInfo() {
1233
    return array(
1234
      'name' => 'Node save',
1235
      'description' => 'Test node_save() for saving content.',
1236
      'group' => 'Node',
1237
    );
1238
  }
1239
1240
  function setUp() {
1241
    parent::setUp('node_test');
1242
    // Create a user that is allowed to post; we'll use this to test the submission.
1243
    $web_user = $this->drupalCreateUser(array('create article content'));
1244
    $this->drupalLogin($web_user);
1245
    $this->web_user = $web_user;
1246
  }
1247
1248
  /**
1249
   * Checks whether custom node IDs are saved properly during an import operation.
1250
   *
1251
   * Workflow:
1252
   *  - first create a piece of content
1253
   *  - save the content
1254
   *  - check if node exists
1255
   */
1256
  function testImport() {
1257
    // Node ID must be a number that is not in the database.
1258
    $max_nid = db_query('SELECT MAX(nid) FROM {node}')->fetchField();
1259
    $test_nid = $max_nid + mt_rand(1000, 1000000);
1260
    $title = $this->randomName(8);
1261
    $node = array(
1262
      'title' => $title,
1263
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(32)))),
1264
      'uid' => $this->web_user->uid,
1265
      'type' => 'article',
1266
      'nid' => $test_nid,
1267
      'is_new' => TRUE,
1268
    );
1269
    $node = node_submit((object) $node);
1270
1271
    // Verify that node_submit did not overwrite the user ID.
1272
    $this->assertEqual($node->uid, $this->web_user->uid, 'Function node_submit() preserves user ID');
1273
1274
    node_save($node);
1275
    // Test the import.
1276
    $node_by_nid = node_load($test_nid);
1277
    $this->assertTrue($node_by_nid, 'Node load by node ID.');
1278
1279
    $node_by_title = $this->drupalGetNodeByTitle($title);
1280
    $this->assertTrue($node_by_title, 'Node load by node title.');
1281
  }
1282
1283
  /**
1284
   * Verifies accuracy of the "created" and "changed" timestamp functionality.
1285
   */
1286
  function testTimestamps() {
1287
    // Use the default timestamps.
1288
    $edit = array(
1289
      'uid' => $this->web_user->uid,
1290
      'type' => 'article',
1291
      'title' => $this->randomName(8),
1292
    );
1293
1294
    node_save((object) $edit);
1295
    $node = $this->drupalGetNodeByTitle($edit['title']);
1296
    $this->assertEqual($node->created, REQUEST_TIME, 'Creating a node sets default "created" timestamp.');
1297
    $this->assertEqual($node->changed, REQUEST_TIME, 'Creating a node sets default "changed" timestamp.');
1298
1299
    // Store the timestamps.
1300
    $created = $node->created;
1301
    $changed = $node->changed;
1302
1303
    node_save($node);
1304
    $node = $this->drupalGetNodeByTitle($edit['title'], TRUE);
1305
    $this->assertEqual($node->created, $created, 'Updating a node preserves "created" timestamp.');
1306
1307
    // Programmatically set the timestamps using hook_node_presave.
1308
    $node->title = 'testing_node_presave';
1309
1310
    node_save($node);
1311
    $node = $this->drupalGetNodeByTitle('testing_node_presave', TRUE);
1312
    $this->assertEqual($node->created, 280299600, 'Saving a node uses "created" timestamp set in presave hook.');
1313
    $this->assertEqual($node->changed, 979534800, 'Saving a node uses "changed" timestamp set in presave hook.');
1314
1315
    // Programmatically set the timestamps on the node.
1316
    $edit = array(
1317
      'uid' => $this->web_user->uid,
1318
      'type' => 'article',
1319
      'title' => $this->randomName(8),
1320
      'created' => 280299600, // Sun, 19 Nov 1978 05:00:00 GMT
1321
      'changed' => 979534800, // Drupal 1.0 release.
1322
    );
1323
1324
    node_save((object) $edit);
1325
    $node = $this->drupalGetNodeByTitle($edit['title']);
1326
    $this->assertEqual($node->created, 280299600, 'Creating a node uses user-set "created" timestamp.');
1327
    $this->assertNotEqual($node->changed, 979534800, 'Creating a node doesn\'t use user-set "changed" timestamp.');
1328
1329
    // Update the timestamps.
1330
    $node->created = 979534800;
1331
    $node->changed = 280299600;
1332
1333
    node_save($node);
1334
    $node = $this->drupalGetNodeByTitle($edit['title'], TRUE);
1335
    $this->assertEqual($node->created, 979534800, 'Updating a node uses user-set "created" timestamp.');
1336
    $this->assertNotEqual($node->changed, 280299600, 'Updating a node doesn\'t use user-set "changed" timestamp.');
1337
  }
1338
1339
  /**
1340
   * Tests determing changes in hook_node_presave() and verifies the static node
1341
   * load cache is cleared upon save.
1342
   */
1343
  function testDeterminingChanges() {
1344
    // Initial creation.
1345
    $node = (object) array(
1346
      'uid' => $this->web_user->uid,
1347
      'type' => 'article',
1348
      'title' => 'test_changes',
1349
    );
1350
    node_save($node);
1351
1352
    // Update the node without applying changes.
1353
    node_save($node);
1354
    $this->assertEqual($node->title, 'test_changes', 'No changes have been determined.');
1355
1356
    // Apply changes.
1357
    $node->title = 'updated';
1358
    node_save($node);
1359
1360
    // The hook implementations node_test_node_presave() and
1361
    // node_test_node_update() determine changes and change the title.
1362
    $this->assertEqual($node->title, 'updated_presave_update', 'Changes have been determined.');
1363
1364
    // Test the static node load cache to be cleared.
1365
    $node = node_load($node->nid);
1366
    $this->assertEqual($node->title, 'updated_presave', 'Static cache has been cleared.');
1367
  }
1368
1369
  /**
1370
   * Tests saving a node on node insert.
1371
   *
1372
   * This test ensures that a node has been fully saved when hook_node_insert()
1373
   * is invoked, so that the node can be saved again in a hook implementation
1374
   * without errors.
1375
   *
1376
   * @see node_test_node_insert()
1377
   */
1378
  function testNodeSaveOnInsert() {
1379 4444412d Julien Enselme
    // node_test_node_insert() triggers a save on insert if the title equals
1380 85ad3d82 Assos Assos
    // 'new'.
1381
    $node = $this->drupalCreateNode(array('title' => 'new'));
1382
    $this->assertEqual($node->title, 'Node ' . $node->nid, 'Node saved on node insert.');
1383
  }
1384
}
1385
1386
/**
1387
 * Tests related to node types.
1388
 */
1389
class NodeTypeTestCase extends DrupalWebTestCase {
1390
  public static function getInfo() {
1391
    return array(
1392
      'name' => 'Node types',
1393
      'description' => 'Ensures that node type functions work correctly.',
1394
      'group' => 'Node',
1395
    );
1396
  }
1397
1398
  /**
1399
   * Ensures that node type functions (node_type_get_*) work correctly.
1400
   *
1401
   * Load available node types and validate the returned data.
1402
   */
1403
  function testNodeTypeGetFunctions() {
1404
    $node_types = node_type_get_types();
1405
    $node_names = node_type_get_names();
1406
1407
    $this->assertTrue(isset($node_types['article']), 'Node type article is available.');
1408
    $this->assertTrue(isset($node_types['page']), 'Node type basic page is available.');
1409
1410
    $this->assertEqual($node_types['article']->name, $node_names['article'], 'Correct node type base has been returned.');
1411
1412
    $this->assertEqual($node_types['article'], node_type_get_type('article'), 'Correct node type has been returned.');
1413
    $this->assertEqual($node_types['article']->name, node_type_get_name('article'), 'Correct node type name has been returned.');
1414
    $this->assertEqual($node_types['page']->base, node_type_get_base('page'), 'Correct node type base has been returned.');
1415
  }
1416
1417
  /**
1418
   * Tests creating a content type programmatically and via a form.
1419
   */
1420
  function testNodeTypeCreation() {
1421
    // Create a content type programmaticaly.
1422
    $type = $this->drupalCreateContentType();
1423
1424
    $type_exists = db_query('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => $type->type))->fetchField();
1425
    $this->assertTrue($type_exists, 'The new content type has been created in the database.');
1426
1427
    // Login a test user.
1428
    $web_user = $this->drupalCreateUser(array('create ' . $type->name . ' content'));
1429
    $this->drupalLogin($web_user);
1430
1431
    $this->drupalGet('node/add/' . str_replace('_', '-', $type->name));
1432
    $this->assertResponse(200, 'The new content type can be accessed at node/add.');
1433
1434
    // Create a content type via the user interface.
1435
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types'));
1436
    $this->drupalLogin($web_user);
1437
    $edit = array(
1438
      'name' => 'foo',
1439
      'title_label' => 'title for foo',
1440
      'type' => 'foo',
1441
    );
1442
    $this->drupalPost('admin/structure/types/add', $edit, t('Save content type'));
1443
    $type_exists = db_query('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => 'foo'))->fetchField();
1444
    $this->assertTrue($type_exists, 'The new content type has been created in the database.');
1445
  }
1446
1447
  /**
1448
   * Tests editing a node type using the UI.
1449
   */
1450
  function testNodeTypeEditing() {
1451
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types'));
1452
    $this->drupalLogin($web_user);
1453
1454
    $instance = field_info_instance('node', 'body', 'page');
1455
    $this->assertEqual($instance['label'], 'Body', 'Body field was found.');
1456
1457
    // Verify that title and body fields are displayed.
1458
    $this->drupalGet('node/add/page');
1459
    $this->assertRaw('Title', 'Title field was found.');
1460
    $this->assertRaw('Body', 'Body field was found.');
1461
1462
    // Rename the title field.
1463
    $edit = array(
1464
      'title_label' => 'Foo',
1465
    );
1466
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
1467
    // Refresh the field information for the rest of the test.
1468
    field_info_cache_clear();
1469
1470
    $this->drupalGet('node/add/page');
1471
    $this->assertRaw('Foo', 'New title label was displayed.');
1472
    $this->assertNoRaw('Title', 'Old title label was not displayed.');
1473
1474
    // Change the name, machine name and description.
1475
    $edit = array(
1476
      'name' => 'Bar',
1477
      'type' => 'bar',
1478
      'description' => 'Lorem ipsum.',
1479
    );
1480
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
1481
    field_info_cache_clear();
1482
1483
    $this->drupalGet('node/add');
1484
    $this->assertRaw('Bar', 'New name was displayed.');
1485
    $this->assertRaw('Lorem ipsum', 'New description was displayed.');
1486
    $this->clickLink('Bar');
1487
    $this->assertEqual(url('node/add/bar', array('absolute' => TRUE)), $this->getUrl(), 'New machine name was used in URL.');
1488
    $this->assertRaw('Foo', 'Title field was found.');
1489
    $this->assertRaw('Body', 'Body field was found.');
1490
1491
    // Remove the body field.
1492
    $this->drupalPost('admin/structure/types/manage/bar/fields/body/delete', NULL, t('Delete'));
1493
    // Resave the settings for this type.
1494
    $this->drupalPost('admin/structure/types/manage/bar', array(), t('Save content type'));
1495
    // Check that the body field doesn't exist.
1496
    $this->drupalGet('node/add/bar');
1497
    $this->assertNoRaw('Body', 'Body field was not found.');
1498
  }
1499
1500
  /**
1501
   * Tests that node_types_rebuild() correctly handles the 'disabled' flag.
1502
   */
1503
  function testNodeTypeStatus() {
1504
    // Enable all core node modules, and all types should be active.
1505
    module_enable(array('blog', 'book', 'poll'), FALSE);
1506
    node_types_rebuild();
1507
    $types = node_type_get_types();
1508
    foreach (array('blog', 'book', 'poll', 'article', 'page') as $type) {
1509
      $this->assertTrue(isset($types[$type]), format_string('%type is found in node types.', array('%type' => $type)));
1510
      $this->assertTrue(isset($types[$type]->disabled) && empty($types[$type]->disabled), format_string('%type type is enabled.', array('%type' => $type)));
1511
    }
1512
1513
    // Disable poll module and the respective type should be marked as disabled.
1514
    module_disable(array('poll'), FALSE);
1515
    node_types_rebuild();
1516
    $types = node_type_get_types();
1517
    $this->assertTrue(!empty($types['poll']->disabled), "Poll module's node type disabled.");
1518
    $this->assertTrue(isset($types['blog']) && empty($types['blog']->disabled), "Blog module's node type still active.");
1519
1520
    // Disable blog module and the respective type should be marked as disabled.
1521
    module_disable(array('blog'), FALSE);
1522
    node_types_rebuild();
1523
    $types = node_type_get_types();
1524
    $this->assertTrue(!empty($types['blog']->disabled), "Blog module's node type disabled.");
1525
    $this->assertTrue(!empty($types['poll']->disabled), "Poll module's node type still disabled.");
1526
1527
    // Disable book module and the respective type should still be active, since
1528
    // it is not provided by hook_node_info().
1529
    module_disable(array('book'), FALSE);
1530
    node_types_rebuild();
1531
    $types = node_type_get_types();
1532
    $this->assertTrue(isset($types['book']) && empty($types['book']->disabled), "Book module's node type still active.");
1533
    $this->assertTrue(!empty($types['blog']->disabled), "Blog module's node type still disabled.");
1534
    $this->assertTrue(!empty($types['poll']->disabled), "Poll module's node type still disabled.");
1535
    $this->assertTrue(isset($types['article']) && empty($types['article']->disabled), "Article node type still active.");
1536
    $this->assertTrue(isset($types['page']) && empty($types['page']->disabled), "Basic page node type still active.");
1537
1538
    // Re-enable the modules and verify that the types are active again.
1539
    module_enable(array('blog', 'book', 'poll'), FALSE);
1540
    node_types_rebuild();
1541
    $types = node_type_get_types();
1542
    foreach (array('blog', 'book', 'poll', 'article', 'page') as $type) {
1543
      $this->assertTrue(isset($types[$type]), format_string('%type is found in node types.', array('%type' => $type)));
1544
      $this->assertTrue(isset($types[$type]->disabled) && empty($types[$type]->disabled), format_string('%type type is enabled.', array('%type' => $type)));
1545
    }
1546
  }
1547
}
1548
1549
/**
1550
 * Test node type customizations persistence.
1551
 */
1552
class NodeTypePersistenceTestCase extends DrupalWebTestCase {
1553
  public static function getInfo() {
1554
    return array(
1555
      'name' => 'Node type persist',
1556
      'description' => 'Ensures that node type customization survives module enabling and disabling.',
1557
      'group' => 'Node',
1558
    );
1559
  }
1560
1561
  /**
1562
   * Tests that node type customizations persist through disable and uninstall.
1563
   */
1564
  function testNodeTypeCustomizationPersistence() {
1565
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types', 'administer modules'));
1566
    $this->drupalLogin($web_user);
1567
    $poll_key = 'modules[Core][poll][enable]';
1568
    $poll_enable = array($poll_key => "1");
1569
    $poll_disable = array($poll_key => FALSE);
1570
1571
    // Enable poll and verify that the node type is in the DB and is not
1572
    // disabled.
1573
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
1574
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
1575
    $this->assertNotIdentical($disabled, FALSE, 'Poll node type found in the database');
1576
    $this->assertEqual($disabled, 0, 'Poll node type is not disabled');
1577
1578
    // Check that poll node type (uncustomized) shows up.
1579
    $this->drupalGet('node/add');
1580
    $this->assertText('poll', 'poll type is found on node/add');
1581
1582
    // Customize poll description.
1583
    $description = $this->randomName();
1584
    $edit = array('description' => $description);
1585
    $this->drupalPost('admin/structure/types/manage/poll', $edit, t('Save content type'));
1586
1587
    // Check that poll node type customization shows up.
1588
    $this->drupalGet('node/add');
1589
    $this->assertText($description, 'Customized description found');
1590
1591
    // Disable poll and check that the node type gets disabled.
1592
    $this->drupalPost('admin/modules', $poll_disable, t('Save configuration'));
1593
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
1594
    $this->assertEqual($disabled, 1, 'Poll node type is disabled');
1595
    $this->drupalGet('node/add');
1596
    $this->assertNoText('poll', 'poll type is not found on node/add');
1597
1598
    // Reenable poll and check that the customization survived the module
1599
    // disable.
1600
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
1601
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
1602
    $this->assertNotIdentical($disabled, FALSE, 'Poll node type found in the database');
1603
    $this->assertEqual($disabled, 0, 'Poll node type is not disabled');
1604
    $this->drupalGet('node/add');
1605
    $this->assertText($description, 'Customized description found');
1606
1607
    // Disable and uninstall poll.
1608
    $this->drupalPost('admin/modules', $poll_disable, t('Save configuration'));
1609
    $edit = array('uninstall[poll]' => 'poll');
1610
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
1611
    $this->drupalPost(NULL, array(), t('Uninstall'));
1612
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
1613
    $this->assertTrue($disabled, 'Poll node type is in the database and is disabled');
1614
    $this->drupalGet('node/add');
1615
    $this->assertNoText('poll', 'poll type is no longer found on node/add');
1616
1617
    // Reenable poll and check that the customization survived the module
1618
    // uninstall.
1619
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
1620
    $this->drupalGet('node/add');
1621
    $this->assertText($description, 'Customized description is found even after uninstall and reenable.');
1622
  }
1623
}
1624
1625
/**
1626
 * Verifies the rebuild functionality for the node_access table.
1627
 */
1628
class NodeAccessRebuildTestCase extends DrupalWebTestCase {
1629
  public static function getInfo() {
1630
    return array(
1631
      'name' => 'Node access rebuild',
1632
      'description' => 'Ensures that node access rebuild functions work correctly.',
1633
      'group' => 'Node',
1634
    );
1635
  }
1636
1637
  function setUp() {
1638
    parent::setUp();
1639
1640
    $web_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports'));
1641
    $this->drupalLogin($web_user);
1642
    $this->web_user = $web_user;
1643
  }
1644
1645
  /**
1646
   * Tests rebuilding the node access permissions table.
1647
   */
1648
  function testNodeAccessRebuild() {
1649
    $this->drupalGet('admin/reports/status');
1650
    $this->clickLink(t('Rebuild permissions'));
1651
    $this->drupalPost(NULL, array(), t('Rebuild permissions'));
1652
    $this->assertText(t('Content permissions have been rebuilt.'));
1653
  }
1654
}
1655
1656
/**
1657
 * Tests node administration page functionality.
1658
 */
1659
class NodeAdminTestCase extends DrupalWebTestCase {
1660
  public static function getInfo() {
1661
    return array(
1662
      'name' => 'Node administration',
1663
      'description' => 'Test node administration page functionality.',
1664
      'group' => 'Node',
1665
    );
1666
  }
1667
1668
  function setUp() {
1669
    parent::setUp();
1670
1671
    // Remove the "view own unpublished content" permission which is set
1672
    // by default for authenticated users so we can test this permission
1673
    // correctly.
1674
    user_role_revoke_permissions(DRUPAL_AUTHENTICATED_RID, array('view own unpublished content'));
1675
1676
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'access content overview', 'administer nodes', 'bypass node access'));
1677
    $this->base_user_1 = $this->drupalCreateUser(array('access content overview'));
1678
    $this->base_user_2 = $this->drupalCreateUser(array('access content overview', 'view own unpublished content'));
1679
    $this->base_user_3 = $this->drupalCreateUser(array('access content overview', 'bypass node access'));
1680
  }
1681
1682
  /**
1683
   * Tests that the table sorting works on the content admin pages.
1684
   */
1685
  function testContentAdminSort() {
1686
    $this->drupalLogin($this->admin_user);
1687
    foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
1688
      $this->drupalCreateNode(array('title' => $prefix . $this->randomName(6)));
1689
    }
1690
1691
    // Test that the default sort by node.changed DESC actually fires properly.
1692
    $nodes_query = db_select('node', 'n')
1693
      ->fields('n', array('nid'))
1694
      ->orderBy('changed', 'DESC')
1695
      ->execute()
1696
      ->fetchCol();
1697
1698
    $nodes_form = array();
1699
    $this->drupalGet('admin/content');
1700
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
1701
      $nodes_form[] = $input;
1702
    }
1703
    $this->assertEqual($nodes_query, $nodes_form, 'Nodes are sorted in the form according to the default query.');
1704
1705
    // Compare the rendered HTML node list to a query for the nodes ordered by
1706
    // title to account for possible database-dependent sort order.
1707
    $nodes_query = db_select('node', 'n')
1708
      ->fields('n', array('nid'))
1709
      ->orderBy('title')
1710
      ->execute()
1711
      ->fetchCol();
1712
1713
    $nodes_form = array();
1714
    $this->drupalGet('admin/content', array('query' => array('sort' => 'asc', 'order' => 'Title')));
1715
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
1716
      $nodes_form[] = $input;
1717
    }
1718
    $this->assertEqual($nodes_query, $nodes_form, 'Nodes are sorted in the form the same as they are in the query.');
1719
  }
1720
1721
  /**
1722
   * Tests content overview with different user permissions.
1723
   *
1724
   * Taxonomy filters are tested separately.
1725
   *
1726
   * @see TaxonomyNodeFilterTestCase
1727
   */
1728
  function testContentAdminPages() {
1729
    $this->drupalLogin($this->admin_user);
1730
1731
    $nodes['published_page'] = $this->drupalCreateNode(array('type' => 'page'));
1732
    $nodes['published_article'] = $this->drupalCreateNode(array('type' => 'article'));
1733
    $nodes['unpublished_page_1'] = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->base_user_1->uid, 'status' => 0));
1734
    $nodes['unpublished_page_2'] = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->base_user_2->uid, 'status' => 0));
1735
1736
    // Verify view, edit, and delete links for any content.
1737
    $this->drupalGet('admin/content');
1738
    $this->assertResponse(200);
1739
    foreach ($nodes as $node) {
1740
      $this->assertLinkByHref('node/' . $node->nid);
1741
      $this->assertLinkByHref('node/' . $node->nid . '/edit');
1742
      $this->assertLinkByHref('node/' . $node->nid . '/delete');
1743
      // Verify tableselect.
1744
      $this->assertFieldByName('nodes[' . $node->nid . ']', '', 'Tableselect found.');
1745
    }
1746
1747
    // Verify filtering by publishing status.
1748
    $edit = array(
1749
      'status' => 'status-1',
1750
    );
1751
    $this->drupalPost(NULL, $edit, t('Filter'));
1752
1753
    $this->assertRaw(t('where %property is %value', array('%property' => t('status'), '%value' => 'published')), 'Content list is filtered by status.');
1754
1755
    $this->assertLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
1756
    $this->assertLinkByHref('node/' . $nodes['published_article']->nid . '/edit');
1757
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');
1758
1759
    // Verify filtering by status and content type.
1760
    $edit = array(
1761
      'type' => 'page',
1762
    );
1763
    $this->drupalPost(NULL, $edit, t('Refine'));
1764
1765
    $this->assertRaw(t('where %property is %value', array('%property' => t('status'), '%value' => 'published')), 'Content list is filtered by status.');
1766
    $this->assertRaw(t('and where %property is %value', array('%property' => t('type'), '%value' => 'Basic page')), 'Content list is filtered by content type.');
1767
1768
    $this->assertLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
1769
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/edit');
1770
1771
    // Verify no operation links are displayed for regular users.
1772
    $this->drupalLogout();
1773
    $this->drupalLogin($this->base_user_1);
1774
    $this->drupalGet('admin/content');
1775
    $this->assertResponse(200);
1776
    $this->assertLinkByHref('node/' . $nodes['published_page']->nid);
1777
    $this->assertLinkByHref('node/' . $nodes['published_article']->nid);
1778
    $this->assertNoLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
1779
    $this->assertNoLinkByHref('node/' . $nodes['published_page']->nid . '/delete');
1780
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/edit');
1781
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/delete');
1782
1783
    // Verify no unpublished content is displayed without permission.
1784
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid);
1785
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');
1786
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/delete');
1787
1788
    // Verify no tableselect.
1789
    $this->assertNoFieldByName('nodes[' . $nodes['published_page']->nid . ']', '', 'No tableselect found.');
1790
1791
    // Verify unpublished content is displayed with permission.
1792
    $this->drupalLogout();
1793
    $this->drupalLogin($this->base_user_2);
1794
    $this->drupalGet('admin/content');
1795
    $this->assertResponse(200);
1796
    $this->assertLinkByHref('node/' . $nodes['unpublished_page_2']->nid);
1797
    // Verify no operation links are displayed.
1798
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->nid . '/edit');
1799
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->nid . '/delete');
1800
1801
    // Verify user cannot see unpublished content of other users.
1802
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid);
1803
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');
1804
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/delete');
1805
1806
    // Verify no tableselect.
1807
    $this->assertNoFieldByName('nodes[' . $nodes['unpublished_page_2']->nid . ']', '', 'No tableselect found.');
1808
1809
    // Verify node access can be bypassed.
1810
    $this->drupalLogout();
1811
    $this->drupalLogin($this->base_user_3);
1812
    $this->drupalGet('admin/content');
1813
    $this->assertResponse(200);
1814
    foreach ($nodes as $node) {
1815
      $this->assertLinkByHref('node/' . $node->nid);
1816
      $this->assertLinkByHref('node/' . $node->nid . '/edit');
1817
      $this->assertLinkByHref('node/' . $node->nid . '/delete');
1818
    }
1819
  }
1820
}
1821
1822
/**
1823
 * Tests node title functionality.
1824
 */
1825
class NodeTitleTestCase extends DrupalWebTestCase {
1826
1827
  /**
1828
   * A user with permission to create and edit content and to administer nodes.
1829
   *
1830
   * @var object
1831
   */
1832
  protected $admin_user;
1833
1834
  public static function getInfo() {
1835
    return array(
1836
      'name' => 'Node title',
1837
      'description' => 'Test node title.',
1838
      'group' => 'Node'
1839
    );
1840
  }
1841
1842
  function setUp() {
1843
    parent::setUp();
1844
    $this->admin_user = $this->drupalCreateUser(array('administer nodes', 'create article content', 'create page content'));
1845
    $this->drupalLogin($this->admin_user);
1846
  }
1847
1848
  /**
1849
   *  Creates one node and tests if the node title has the correct value.
1850
   */
1851
  function testNodeTitle() {
1852
    // Create "Basic page" content with title.
1853
    // Add the node to the frontpage so we can test if teaser links are clickable.
1854
    $settings = array(
1855
      'title' => $this->randomName(8),
1856
      'promote' => 1,
1857
    );
1858
    $node = $this->drupalCreateNode($settings);
1859
1860
    // Test <title> tag.
1861
    $this->drupalGet("node/$node->nid");
1862
    $xpath = '//title';
1863
    $this->assertEqual(current($this->xpath($xpath)), $node->title .' | Drupal', 'Page title is equal to node title.', 'Node');
1864
1865
    // Test breadcrumb in comment preview.
1866
    $this->drupalGet("comment/reply/$node->nid");
1867
    $xpath = '//div[@class="breadcrumb"]/a[last()]';
1868
    $this->assertEqual(current($this->xpath($xpath)), $node->title, 'Node breadcrumb is equal to node title.', 'Node');
1869
1870
    // Test node title in comment preview.
1871
    $this->assertEqual(current($this->xpath('//div[@id=:id]/h2/a', array(':id' => 'node-' . $node->nid))), $node->title, 'Node preview title is equal to node title.', 'Node');
1872
1873
    // Test node title is clickable on teaser list (/node).
1874
    $this->drupalGet('node');
1875
    $this->clickLink($node->title);
1876
  }
1877
}
1878
1879
/**
1880
 * Test the node_feed() functionality.
1881
 */
1882
class NodeFeedTestCase extends DrupalWebTestCase {
1883
  public static function getInfo() {
1884
    return array(
1885
      'name' => 'Node feed',
1886
      'description' => 'Ensures that node_feed() functions correctly.',
1887
      'group' => 'Node',
1888
   );
1889
  }
1890
1891
  /**
1892
   * Ensures that node_feed() accepts and prints extra channel elements.
1893
   */
1894
  function testNodeFeedExtraChannelElements() {
1895
    ob_start();
1896
    node_feed(array(), array('copyright' => 'Drupal is a registered trademark of Dries Buytaert.'));
1897
    $output = ob_get_clean();
1898
1899
    $this->assertTrue(strpos($output, '<copyright>Drupal is a registered trademark of Dries Buytaert.</copyright>') !== FALSE);
1900
  }
1901
}
1902
1903
/**
1904
 * Functional tests for the node module blocks.
1905
 */
1906
class NodeBlockFunctionalTest extends DrupalWebTestCase {
1907
  public static function getInfo() {
1908
    return array(
1909
      'name' => 'Node blocks',
1910
      'description' => 'Test node block functionality.',
1911
      'group' => 'Node',
1912
    );
1913
  }
1914
1915
  function setUp() {
1916
    parent::setUp('node', 'block');
1917
1918
    // Create users and test node.
1919
    $this->admin_user = $this->drupalCreateUser(array('administer content types', 'administer nodes', 'administer blocks'));
1920
    $this->web_user = $this->drupalCreateUser(array('access content', 'create article content'));
1921
  }
1922
1923
  /**
1924
   * Tests the recent comments block.
1925
   */
1926
  function testRecentNodeBlock() {
1927
    $this->drupalLogin($this->admin_user);
1928
1929
    // Disallow anonymous users to view content.
1930
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
1931
      'access content' => FALSE,
1932
    ));
1933
1934
    // Set the block to a region to confirm block is available.
1935
    $edit = array(
1936
      'blocks[node_recent][region]' => 'sidebar_first',
1937
    );
1938
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
1939
    $this->assertText(t('The block settings have been updated.'), 'Block saved to first sidebar region.');
1940
1941
    // Set block title and variables.
1942
    $block = array(
1943
      'title' => $this->randomName(),
1944
      'node_recent_block_count' => 2,
1945
    );
1946
    $this->drupalPost('admin/structure/block/manage/node/recent/configure', $block, t('Save block'));
1947
    $this->assertText(t('The block configuration has been saved.'), 'Block saved.');
1948
1949
    // Test that block is not visible without nodes
1950
    $this->drupalGet('');
1951
    $this->assertText(t('No content available.'), 'Block with "No content available." found.');
1952
1953
    // Add some test nodes.
1954
    $default_settings = array('uid' => $this->web_user->uid, 'type' => 'article');
1955
    $node1 = $this->drupalCreateNode($default_settings);
1956
    $node2 = $this->drupalCreateNode($default_settings);
1957
    $node3 = $this->drupalCreateNode($default_settings);
1958
1959
    // Change the changed time for node so that we can test ordering.
1960
    db_update('node')
1961
      ->fields(array(
1962
        'changed' => $node1->changed + 100,
1963
      ))
1964
      ->condition('nid', $node2->nid)
1965
      ->execute();
1966
    db_update('node')
1967
      ->fields(array(
1968
        'changed' => $node1->changed + 200,
1969
      ))
1970
      ->condition('nid', $node3->nid)
1971
      ->execute();
1972
1973
    // Test that a user without the 'access content' permission cannot
1974
    // see the block.
1975
    $this->drupalLogout();
1976
    $this->drupalGet('');
1977
    $this->assertNoText($block['title'], 'Block was not found.');
1978
1979
    // Test that only the 2 latest nodes are shown.
1980
    $this->drupalLogin($this->web_user);
1981
    $this->assertNoText($node1->title, 'Node not found in block.');
1982
    $this->assertText($node2->title, 'Node found in block.');
1983
    $this->assertText($node3->title, 'Node found in block.');
1984
1985
    // Check to make sure nodes are in the right order.
1986
    $this->assertTrue($this->xpath('//div[@id="block-node-recent"]/div/table/tbody/tr[position() = 1]/td/div/a[text() = "' . $node3->title . '"]'), 'Nodes were ordered correctly in block.');
1987
1988
    // Set the number of recent nodes to show to 10.
1989
    $this->drupalLogout();
1990
    $this->drupalLogin($this->admin_user);
1991
    $block = array(
1992
      'node_recent_block_count' => 10,
1993
    );
1994
    $this->drupalPost('admin/structure/block/manage/node/recent/configure', $block, t('Save block'));
1995
    $this->assertText(t('The block configuration has been saved.'), 'Block saved.');
1996
1997
    // Post an additional node.
1998
    $node4 = $this->drupalCreateNode($default_settings);
1999
2000
    // Test that all four nodes are shown.
2001
    $this->drupalGet('');
2002
    $this->assertText($node1->title, 'Node found in block.');
2003
    $this->assertText($node2->title, 'Node found in block.');
2004
    $this->assertText($node3->title, 'Node found in block.');
2005
    $this->assertText($node4->title, 'Node found in block.');
2006
2007
    // Create the custom block.
2008
    $custom_block = array();
2009
    $custom_block['info'] = $this->randomName();
2010
    $custom_block['title'] = $this->randomName();
2011
    $custom_block['types[article]'] = TRUE;
2012
    $custom_block['body[value]'] = $this->randomName(32);
2013
    $custom_block['regions[' . variable_get('theme_default', 'bartik') . ']'] = 'content';
2014
    if ($admin_theme = variable_get('admin_theme')) {
2015
      $custom_block['regions[' . $admin_theme . ']'] = 'content';
2016
    }
2017
    $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
2018
2019
    $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
2020
    $this->assertTrue($bid, 'Custom block with visibility rule was created.');
2021
2022
    // Verify visibility rules.
2023
    $this->drupalGet('');
2024
    $this->assertNoText($custom_block['title'], 'Block was displayed on the front page.');
2025
    $this->drupalGet('node/add/article');
2026
    $this->assertText($custom_block['title'], 'Block was displayed on the node/add/article page.');
2027
    $this->drupalGet('node/' . $node1->nid);
2028
    $this->assertText($custom_block['title'], 'Block was displayed on the node/N.');
2029
2030
    // Delete the created custom block & verify that it's been deleted.
2031
    $this->drupalPost('admin/structure/block/manage/block/' . $bid . '/delete', array(), t('Delete'));
2032
    $bid = db_query("SELECT 1 FROM {block_node_type} WHERE module = 'block' AND delta = :delta", array(':delta' => $bid))->fetchField();
2033
    $this->assertFalse($bid, 'Custom block was deleted.');
2034
  }
2035
}
2036
/**
2037
 * Tests basic options of multi-step node forms.
2038
 */
2039
class MultiStepNodeFormBasicOptionsTest extends DrupalWebTestCase {
2040
  public static function getInfo() {
2041
    return array(
2042
      'name' => 'Multistep node form basic options',
2043
      'description' => 'Test the persistence of basic options through multiple steps.',
2044
      'group' => 'Node',
2045
    );
2046
  }
2047
2048
  function setUp() {
2049
    parent::setUp('poll');
2050
    $web_user = $this->drupalCreateUser(array('administer nodes', 'create poll content'));
2051
    $this->drupalLogin($web_user);
2052
  }
2053
2054
  /**
2055
   * Tests changing the default values of basic options to ensure they persist.
2056
   */
2057
  function testMultiStepNodeFormBasicOptions() {
2058
    $edit = array(
2059
      'title' => 'a',
2060
      'status' => FALSE,
2061
      'promote' => FALSE,
2062
      'sticky' => 1,
2063
      'choice[new:0][chtext]' => 'a',
2064
      'choice[new:1][chtext]' => 'a',
2065
    );
2066
    $this->drupalPost('node/add/poll', $edit, t('More choices'));
2067
    $this->assertNoFieldChecked('edit-status', 'status stayed unchecked');
2068
    $this->assertNoFieldChecked('edit-promote', 'promote stayed unchecked');
2069
    $this->assertFieldChecked('edit-sticky', 'sticky stayed checked');
2070
  }
2071
}
2072
2073
/**
2074
 * Test to ensure that a node's content is always rebuilt.
2075
 */
2076
class NodeBuildContent extends DrupalWebTestCase {
2077
2078
  public static function getInfo() {
2079
    return array(
2080
      'name' => 'Rebuild content',
2081
      'description' => 'Test the rebuilding of content for different build modes.',
2082
      'group' => 'Node',
2083
    );
2084
  }
2085
2086
 /**
2087
  * Ensures that content array is rebuilt on every call to node_build_content().
2088
  */
2089
  function testNodeRebuildContent() {
2090
    $node = $this->drupalCreateNode();
2091
2092
    // Set a property in the content array so we can test for its existence later on.
2093
    $node->content['test_content_property'] = array('#value' => $this->randomString());
2094
    $content = node_build_content($node);
2095
2096
    // If the property doesn't exist it means the node->content was rebuilt.
2097
    $this->assertFalse(isset($content['test_content_property']), 'Node content was emptied prior to being built.');
2098
  }
2099
}
2100
2101
/**
2102
 * Tests node_query_node_access_alter().
2103
 */
2104
class NodeQueryAlter extends DrupalWebTestCase {
2105
2106
  public static function getInfo() {
2107
    return array(
2108
      'name' => 'Node query alter',
2109
      'description' => 'Test that node access queries are properly altered by the node module.',
2110
      'group' => 'Node',
2111
    );
2112
  }
2113
2114
  /**
2115
   * User with permission to view content.
2116
   *
2117
   * @var object
2118
   */
2119
  protected $accessUser;
2120
2121
  /**
2122
   * User without permission to view content.
2123
   *
2124
   * @var object
2125
   */
2126
  protected $noAccessUser;
2127
2128
  function setUp() {
2129
    parent::setUp('node_access_test');
2130
    node_access_rebuild();
2131
2132
    // Create some content.
2133
    $this->drupalCreateNode();
2134
    $this->drupalCreateNode();
2135
    $this->drupalCreateNode();
2136
    $this->drupalCreateNode();
2137
2138
    // Create user with simple node access permission. The 'node test view'
2139
    // permission is implemented and granted by the node_access_test module.
2140
    $this->accessUser = $this->drupalCreateUser(array('access content overview', 'access content', 'node test view'));
2141
    $this->noAccessUser = $this->drupalCreateUser(array('access content overview', 'access content'));
2142
    $this->noAccessUser2 = $this->drupalCreateUser(array('access content overview', 'access content'));
2143
  }
2144
2145
  /**
2146
   * Tests that node access permissions are followed.
2147
   */
2148
  function testNodeQueryAlterWithUI() {
2149
    // Verify that a user with access permission can see at least one node.
2150
    $this->drupalLogin($this->accessUser);
2151
    $this->drupalGet('node_access_test_page');
2152
    $this->assertText('Yes, 4 nodes', "4 nodes were found for access user");
2153
    $this->assertNoText('Exception', "No database exception");
2154
2155
    // Test the content overview page.
2156
    $this->drupalGet('admin/content');
2157
    $table_rows = $this->xpath('//tbody/tr');
2158
    $this->assertEqual(4, count($table_rows), "4 nodes were found for access user");
2159
2160
    // Verify that a user with no access permission cannot see nodes.
2161
    $this->drupalLogin($this->noAccessUser);
2162
    $this->drupalGet('node_access_test_page');
2163
    $this->assertText('No nodes', "No nodes were found for no access user");
2164
    $this->assertNoText('Exception', "No database exception");
2165
2166
    $this->drupalGet('admin/content');
2167
    $this->assertText(t('No content available.'));
2168
  }
2169
2170
  /**
2171
   * Tests 'node_access' query alter, for user with access.
2172
   *
2173
   * Verifies that a non-standard table alias can be used, and that a user with
2174
   * node access can view the nodes.
2175
   */
2176
  function testNodeQueryAlterLowLevelWithAccess() {
2177
    // User with access should be able to view 4 nodes.
2178
    try {
2179
      $query = db_select('node', 'mytab')
2180
        ->fields('mytab');
2181
      $query->addTag('node_access');
2182
      $query->addMetaData('op', 'view');
2183
      $query->addMetaData('account', $this->accessUser);
2184
2185
      $result = $query->execute()->fetchAll();
2186
      $this->assertEqual(count($result), 4, 'User with access can see correct nodes');
2187
    }
2188
    catch (Exception $e) {
2189
      $this->fail(t('Altered query is malformed'));
2190
    }
2191
  }
2192
2193
  /**
2194
   * Tests 'node_access' query alter, for user without access.
2195
   *
2196
   * Verifies that a non-standard table alias can be used, and that a user
2197
   * without node access cannot view the nodes.
2198
   */
2199
  function testNodeQueryAlterLowLevelNoAccess() {
2200
    // User without access should be able to view 0 nodes.
2201
    try {
2202
      $query = db_select('node', 'mytab')
2203
        ->fields('mytab');
2204
      $query->addTag('node_access');
2205
      $query->addMetaData('op', 'view');
2206
      $query->addMetaData('account', $this->noAccessUser);
2207
2208
      $result = $query->execute()->fetchAll();
2209
      $this->assertEqual(count($result), 0, 'User with no access cannot see nodes');
2210
    }
2211
    catch (Exception $e) {
2212
      $this->fail(t('Altered query is malformed'));
2213
    }
2214
  }
2215
2216
  /**
2217
   * Tests 'node_access' query alter, for edit access.
2218
   *
2219
   * Verifies that a non-standard table alias can be used, and that a user with
2220
   * view-only node access cannot edit the nodes.
2221
   */
2222
  function testNodeQueryAlterLowLevelEditAccess() {
2223
    // User with view-only access should not be able to edit nodes.
2224
    try {
2225
      $query = db_select('node', 'mytab')
2226
        ->fields('mytab');
2227
      $query->addTag('node_access');
2228
      $query->addMetaData('op', 'update');
2229
      $query->addMetaData('account', $this->accessUser);
2230
2231
      $result = $query->execute()->fetchAll();
2232
      $this->assertEqual(count($result), 0, 'User with view-only access cannot edit nodes');
2233
    }
2234
    catch (Exception $e) {
2235
      $this->fail($e->getMessage());
2236
      $this->fail((string) $query);
2237
      $this->fail(t('Altered query is malformed'));
2238
    }
2239
  }
2240
2241
  /**
2242
   * Tests 'node_access' query alter override.
2243
   *
2244
   * Verifies that node_access_view_all_nodes() is called from
2245
   * node_query_node_access_alter(). We do this by checking that a user who
2246
   * normally would not have view privileges is able to view the nodes when we
2247
   * add a record to {node_access} paired with a corresponding privilege in
2248
   * hook_node_grants().
2249
   */
2250
  function testNodeQueryAlterOverride() {
2251
    $record = array(
2252
      'nid' => 0,
2253
      'gid' => 0,
2254
      'realm' => 'node_access_all',
2255
      'grant_view' => 1,
2256
      'grant_update' => 0,
2257
      'grant_delete' => 0,
2258
    );
2259
    drupal_write_record('node_access', $record);
2260
2261
    // Test that the noAccessUser still doesn't have the 'view'
2262
    // privilege after adding the node_access record.
2263
    drupal_static_reset('node_access_view_all_nodes');
2264
    try {
2265
      $query = db_select('node', 'mytab')
2266
        ->fields('mytab');
2267
      $query->addTag('node_access');
2268
      $query->addMetaData('op', 'view');
2269
      $query->addMetaData('account', $this->noAccessUser);
2270
2271
      $result = $query->execute()->fetchAll();
2272
      $this->assertEqual(count($result), 0, 'User view privileges are not overridden');
2273
    }
2274
    catch (Exception $e) {
2275
      $this->fail(t('Altered query is malformed'));
2276
    }
2277
2278
    // Have node_test_node_grants return a node_access_all privilege,
2279
    // to grant the noAccessUser 'view' access.  To verify that
2280
    // node_access_view_all_nodes is properly checking the specified
2281
    // $account instead of the global $user, we will log in as
2282
    // noAccessUser2.
2283
    $this->drupalLogin($this->noAccessUser2);
2284
    variable_set('node_test_node_access_all_uid', $this->noAccessUser->uid);
2285
    drupal_static_reset('node_access_view_all_nodes');
2286
    try {
2287
      $query = db_select('node', 'mytab')
2288
        ->fields('mytab');
2289
      $query->addTag('node_access');
2290
      $query->addMetaData('op', 'view');
2291
      $query->addMetaData('account', $this->noAccessUser);
2292
2293
      $result = $query->execute()->fetchAll();
2294
      $this->assertEqual(count($result), 4, 'User view privileges are overridden');
2295
    }
2296
    catch (Exception $e) {
2297
      $this->fail(t('Altered query is malformed'));
2298
    }
2299
    variable_del('node_test_node_access_all_uid');
2300
  }
2301
}
2302
2303
2304
/**
2305
 * Tests node_query_entity_field_access_alter().
2306
 */
2307
class NodeEntityFieldQueryAlter extends DrupalWebTestCase {
2308
2309
  public static function getInfo() {
2310
    return array(
2311
      'name' => 'Node entity query alter',
2312
      'description' => 'Test that node access entity queries are properly altered by the node module.',
2313
      'group' => 'Node',
2314
    );
2315
  }
2316
2317
  /**
2318
   * User with permission to view content.
2319
   *
2320
   * @var object
2321
   */
2322
  protected $accessUser;
2323
2324
  /**
2325
   * User without permission to view content.
2326
   *
2327
   * @var object
2328
   */
2329
  protected $noAccessUser;
2330
2331
  function setUp() {
2332
    parent::setUp('node_access_test');
2333
    node_access_rebuild();
2334
2335
    // Creating 4 nodes with an entity field so we can test that sort of query
2336
    // alter. All field values starts with 'A' so we can identify and fetch them
2337
    // in the node_access_test module.
2338
    $settings = array('language' => LANGUAGE_NONE);
2339
    for ($i = 0; $i < 4; $i++) {
2340
      $body = array(
2341
        'value' => 'A' . $this->randomName(32),
2342
        'format' => filter_default_format(),
2343
      );
2344
      $settings['body'][LANGUAGE_NONE][0] = $body;
2345
      $this->drupalCreateNode($settings);
2346
    }
2347
2348
    // Create user with simple node access permission. The 'node test view'
2349
    // permission is implemented and granted by the node_access_test module.
2350
    $this->accessUser = $this->drupalCreateUser(array('access content', 'node test view'));
2351
    $this->noAccessUser = $this->drupalCreateUser(array('access content'));
2352
  }
2353
2354
  /**
2355
   * Tests that node access permissions are followed.
2356
   */
2357
  function testNodeQueryAlterWithUI() {
2358
    // Verify that a user with access permission can see at least one node.
2359
    $this->drupalLogin($this->accessUser);
2360
    $this->drupalGet('node_access_entity_test_page');
2361
    $this->assertText('Yes, 4 nodes', "4 nodes were found for access user");
2362
    $this->assertNoText('Exception', "No database exception");
2363
2364
    // Verify that a user with no access permission cannot see nodes.
2365
    $this->drupalLogin($this->noAccessUser);
2366
    $this->drupalGet('node_access_entity_test_page');
2367
    $this->assertText('No nodes', "No nodes were found for no access user");
2368
    $this->assertNoText('Exception', "No database exception");
2369
  }
2370
}
2371
2372
/**
2373
 * Test node token replacement in strings.
2374
 */
2375
class NodeTokenReplaceTestCase extends DrupalWebTestCase {
2376
  public static function getInfo() {
2377
    return array(
2378
      'name' => 'Node token replacement',
2379
      'description' => 'Generates text using placeholders for dummy content to check node token replacement.',
2380
      'group' => 'Node',
2381
    );
2382
  }
2383
2384
  /**
2385
   * Creates a node, then tests the tokens generated from it.
2386
   */
2387
  function testNodeTokenReplacement() {
2388
    global $language;
2389
    $url_options = array(
2390
      'absolute' => TRUE,
2391
      'language' => $language,
2392
    );
2393
2394
    // Create a user and a node.
2395
    $account = $this->drupalCreateUser();
2396
    $settings = array(
2397
      'type' => 'article',
2398
      'uid' => $account->uid,
2399
      'title' => '<blink>Blinking Text</blink>',
2400
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(32), 'summary' => $this->randomName(16)))),
2401
    );
2402
    $node = $this->drupalCreateNode($settings);
2403
2404
    // Load node so that the body and summary fields are structured properly.
2405
    $node = node_load($node->nid);
2406
    $instance = field_info_instance('node', 'body', $node->type);
2407
2408
    // Generate and test sanitized tokens.
2409
    $tests = array();
2410
    $langcode = entity_language('node', $node);
2411
    $tests['[node:nid]'] = $node->nid;
2412
    $tests['[node:vid]'] = $node->vid;
2413
    $tests['[node:tnid]'] = $node->tnid;
2414
    $tests['[node:type]'] = 'article';
2415
    $tests['[node:type-name]'] = 'Article';
2416
    $tests['[node:title]'] = check_plain($node->title);
2417
    $tests['[node:body]'] = _text_sanitize($instance, $langcode, $node->body[$langcode][0], 'value');
2418
    $tests['[node:summary]'] = _text_sanitize($instance, $langcode, $node->body[$langcode][0], 'summary');
2419
    $tests['[node:language]'] = check_plain($langcode);
2420
    $tests['[node:url]'] = url('node/' . $node->nid, $url_options);
2421
    $tests['[node:edit-url]'] = url('node/' . $node->nid . '/edit', $url_options);
2422
    $tests['[node:author]'] = check_plain(format_username($account));
2423
    $tests['[node:author:uid]'] = $node->uid;
2424
    $tests['[node:author:name]'] = check_plain(format_username($account));
2425
    $tests['[node:created:since]'] = format_interval(REQUEST_TIME - $node->created, 2, $language->language);
2426
    $tests['[node:changed:since]'] = format_interval(REQUEST_TIME - $node->changed, 2, $language->language);
2427
2428
    // Test to make sure that we generated something for each token.
2429
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
2430
2431
    foreach ($tests as $input => $expected) {
2432
      $output = token_replace($input, array('node' => $node), array('language' => $language));
2433
      $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input)));
2434
    }
2435
2436
    // Generate and test unsanitized tokens.
2437
    $tests['[node:title]'] = $node->title;
2438
    $tests['[node:body]'] = $node->body[$langcode][0]['value'];
2439
    $tests['[node:summary]'] = $node->body[$langcode][0]['summary'];
2440
    $tests['[node:language]'] = $langcode;
2441
    $tests['[node:author:name]'] = format_username($account);
2442
2443
    foreach ($tests as $input => $expected) {
2444
      $output = token_replace($input, array('node' => $node), array('language' => $language, 'sanitize' => FALSE));
2445
      $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input)));
2446
    }
2447 4444412d Julien Enselme
2448
    // Repeat for a node without a summary.
2449
    $settings['body'] = array(LANGUAGE_NONE => array(array('value' => $this->randomName(32), 'summary' => '')));
2450
    $node = $this->drupalCreateNode($settings);
2451
2452
    // Load node (without summary) so that the body and summary fields are
2453
    // structured properly.
2454
    $node = node_load($node->nid);
2455
    $instance = field_info_instance('node', 'body', $node->type);
2456
2457
    // Generate and test sanitized token - use full body as expected value.
2458
    $tests = array();
2459
    $tests['[node:summary]'] = _text_sanitize($instance, $langcode, $node->body[$langcode][0], 'value');
2460
2461
    // Test to make sure that we generated something for each token.
2462
    $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.');
2463
2464
    foreach ($tests as $input => $expected) {
2465
      $output = token_replace($input, array('node' => $node), array('language' => $language));
2466
      $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input)));
2467
    }
2468
2469
    // Generate and test unsanitized tokens.
2470
    $tests['[node:summary]'] = $node->body[$langcode][0]['value'];
2471
2472
    foreach ($tests as $input => $expected) {
2473
      $output = token_replace($input, array('node' => $node), array('language' => $language, 'sanitize' => FALSE));
2474
      $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input)));
2475
    }
2476 85ad3d82 Assos Assos
  }
2477
}
2478
2479
/**
2480
 * Tests user permissions for node revisions.
2481
 */
2482
class NodeRevisionPermissionsTestCase extends DrupalWebTestCase {
2483
2484
  /**
2485
   * Nodes used by the test.
2486
   *
2487
   * @var array
2488
   */
2489
  protected $node_revisions = array();
2490
2491
  /**
2492
   * Users with different revision permission used by the test.
2493
   *
2494
   * @var array
2495
   */
2496
  protected $accounts = array();
2497
2498
  /**
2499
   * Map revision permission names to node revision access ops.
2500
   *
2501
   * @var array
2502
   */
2503
  protected $map = array(
2504
    'view' => 'view revisions',
2505
    'update' => 'revert revisions',
2506
    'delete' => 'delete revisions',
2507
  );
2508
2509
  public static function getInfo() {
2510
    return array(
2511
      'name' => 'Node revision permissions',
2512
      'description' => 'Tests user permissions for node revision operations.',
2513
      'group' => 'Node',
2514
    );
2515
  }
2516
2517
  function setUp() {
2518
    parent::setUp();
2519
2520
    // Create a node with several revisions.
2521
    $node = $this->drupalCreateNode();
2522
    $this->node_revisions[] = $node;
2523
2524
    for ($i = 0; $i < 3; $i++) {
2525
      // Create a revision for the same nid and settings with a random log.
2526
      $revision = clone $node;
2527
      $revision->revision = 1;
2528
      $revision->log = $this->randomName(32);
2529
      node_save($revision);
2530
      $this->node_revisions[] = $revision;
2531
    }
2532
2533
    // Create three users, one with each revision permission.
2534
    foreach ($this->map as $op => $permission) {
2535
      // Create the user.
2536
      $account = $this->drupalCreateUser(
2537
        array(
2538
          'access content',
2539
          'edit any page content',
2540
          'delete any page content',
2541
          $permission,
2542
        )
2543
      );
2544
      $account->op = $op;
2545
      $this->accounts[] = $account;
2546
    }
2547
2548
    // Create an admin account (returns TRUE for all revision permissions).
2549
    $admin_account = $this->drupalCreateUser(array('access content', 'administer nodes'));
2550
    $admin_account->is_admin = TRUE;
2551
    $this->accounts['admin'] = $admin_account;
2552
2553
    // Create a normal account (returns FALSE for all revision permissions).
2554
    $normal_account = $this->drupalCreateUser();
2555
    $normal_account->op = FALSE;
2556
    $this->accounts[] = $normal_account;
2557
  }
2558
2559
  /**
2560
   * Tests the _node_revision_access() function.
2561
   */
2562
  function testNodeRevisionAccess() {
2563
    $revision = $this->node_revisions[1];
2564
2565
    $parameters = array(
2566
      'op' => array_keys($this->map),
2567
      'account' => $this->accounts,
2568
    );
2569
2570
    $permutations = $this->generatePermutations($parameters);
2571
    foreach ($permutations as $case) {
2572
      if (!empty($case['account']->is_admin) || $case['op'] == $case['account']->op) {
2573
        $this->assertTrue(_node_revision_access($revision, $case['op'], $case['account']), "{$this->map[$case['op']]} granted.");
2574
      }
2575
      else {
2576
        $this->assertFalse(_node_revision_access($revision, $case['op'], $case['account']), "{$this->map[$case['op']]} not granted.");
2577
      }
2578
    }
2579
2580
    // Test that access is FALSE for a node administrator with an invalid $node
2581
    // or $op parameters.
2582
    $admin_account = $this->accounts['admin'];
2583
    $this->assertFalse(_node_revision_access(FALSE, 'view', $admin_account), '_node_revision_access() returns FALSE with an invalid node.');
2584
    $this->assertFalse(_node_revision_access($revision, 'invalid-op', $admin_account), '_node_revision_access() returns FALSE with an invalid op.');
2585
2586
    // Test that the $account parameter defaults to the "logged in" user.
2587
    $original_user = $GLOBALS['user'];
2588
    $GLOBALS['user'] = $admin_account;
2589
    $this->assertTrue(_node_revision_access($revision, 'view'), '_node_revision_access() returns TRUE when used with global user.');
2590
    $GLOBALS['user'] = $original_user;
2591
  }
2592
}
2593
2594
/**
2595
 * Tests pagination with a node access module enabled.
2596
 */
2597
class NodeAccessPagerTestCase extends DrupalWebTestCase {
2598
2599
  public static function getInfo() {
2600
    return array(
2601
      'name' => 'Node access pagination',
2602
      'description' => 'Test access controlled node views have the right amount of comment pages.',
2603
      'group' => 'Node',
2604
    );
2605
  }
2606
2607
  public function setUp() {
2608
    parent::setUp('node_access_test', 'comment', 'forum');
2609
    node_access_rebuild();
2610
    $this->web_user = $this->drupalCreateUser(array('access content', 'access comments', 'node test view'));
2611
  }
2612
2613
  /**
2614
   * Tests the comment pager for nodes with multiple grants per realm.
2615
   */
2616
  public function testCommentPager() {
2617
    // Create a node.
2618
    $node = $this->drupalCreateNode();
2619
2620
    // Create 60 comments.
2621
    for ($i = 0; $i < 60; $i++) {
2622
      $comment = new stdClass();
2623
      $comment->cid = 0;
2624
      $comment->pid = 0;
2625
      $comment->uid = $this->web_user->uid;
2626
      $comment->nid = $node->nid;
2627
      $comment->subject = $this->randomName();
2628
      $comment->comment_body = array(
2629
        LANGUAGE_NONE => array(
2630
          array('value' => $this->randomName()),
2631
        ),
2632
      );
2633
      comment_save($comment);
2634
    }
2635
2636
    $this->drupalLogin($this->web_user);
2637
2638
    // View the node page. With the default 50 comments per page there should
2639
    // be two pages (0, 1) but no third (2) page.
2640
    $this->drupalGet('node/' . $node->nid);
2641
    $this->assertText($node->title);
2642
    $this->assertText(t('Comments'));
2643
    $this->assertRaw('page=1');
2644
    $this->assertNoRaw('page=2');
2645
  }
2646
2647
  /**
2648
   * Tests the forum node pager for nodes with multiple grants per realm.
2649
   */
2650
  public function testForumPager() {
2651
    // Look up the forums vocabulary ID.
2652
    $vid = variable_get('forum_nav_vocabulary', 0);
2653
    $this->assertTrue($vid, 'Forum navigation vocabulary ID is set.');
2654
2655
    // Look up the general discussion term.
2656
    $tree = taxonomy_get_tree($vid, 0, 1);
2657
    $tid = reset($tree)->tid;
2658
    $this->assertTrue($tid, 'General discussion term is found in the forum vocabulary.');
2659
2660
    // Create 30 nodes.
2661
    for ($i = 0; $i < 30; $i++) {
2662
      $this->drupalCreateNode(array(
2663
        'nid' => NULL,
2664
        'type' => 'forum',
2665
        'taxonomy_forums' => array(
2666
          LANGUAGE_NONE => array(
2667
            array('tid' => $tid, 'vid' => $vid, 'vocabulary_machine_name' => 'forums'),
2668
          ),
2669
        ),
2670
      ));
2671
    }
2672
2673
    // View the general discussion forum page. With the default 25 nodes per
2674
    // page there should be two pages for 30 nodes, no more.
2675
    $this->drupalLogin($this->web_user);
2676
    $this->drupalGet('forum/' . $tid);
2677
    $this->assertRaw('page=1');
2678
    $this->assertNoRaw('page=2');
2679
  }
2680
}
2681
2682
2683
/**
2684
 * Tests the interaction of the node access system with fields.
2685
 */
2686
class NodeAccessFieldTestCase extends NodeWebTestCase {
2687
2688
  public static function getInfo() {
2689
    return array(
2690
      'name' => 'Node access and fields',
2691
      'description' => 'Tests the interaction of the node access system with fields.',
2692
      'group' => 'Node',
2693
    );
2694
  }
2695
2696
  public function setUp() {
2697
    parent::setUp('node_access_test', 'field_ui');
2698
    node_access_rebuild();
2699
2700
    // Create some users.
2701
    $this->admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
2702
    $this->content_admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));
2703
2704
    // Add a custom field to the page content type.
2705
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
2706
    $this->field = field_create_field(array('field_name' => $this->field_name, 'type' => 'text'));
2707
    $this->instance = field_create_instance(array(
2708
      'field_name' => $this->field_name,
2709
      'entity_type' => 'node',
2710
      'bundle' => 'page',
2711
    ));
2712
  }
2713
2714
  /**
2715
   * Tests administering fields when node access is restricted.
2716
   */
2717
  function testNodeAccessAdministerField() {
2718
    // Create a page node.
2719
    $langcode = LANGUAGE_NONE;
2720
    $field_data = array();
2721
    $value = $field_data[$langcode][0]['value'] = $this->randomName();
2722
    $node = $this->drupalCreateNode(array($this->field_name => $field_data));
2723
2724
    // Log in as the administrator and confirm that the field value is present.
2725
    $this->drupalLogin($this->admin_user);
2726
    $this->drupalGet("node/{$node->nid}");
2727
    $this->assertText($value, 'The saved field value is visible to an administrator.');
2728
2729
    // Log in as the content admin and try to view the node.
2730
    $this->drupalLogin($this->content_admin_user);
2731
    $this->drupalGet("node/{$node->nid}");
2732
    $this->assertText('Access denied', 'Access is denied for the content admin.');
2733
2734
    // Modify the field default as the content admin.
2735
    $edit = array();
2736
    $default = 'Sometimes words have two meanings';
2737
    $edit["{$this->field_name}[$langcode][0][value]"] = $default;
2738
    $this->drupalPost(
2739
      "admin/structure/types/manage/page/fields/{$this->field_name}",
2740
      $edit,
2741
      t('Save settings')
2742
    );
2743
2744
    // Log in as the administrator.
2745
    $this->drupalLogin($this->admin_user);
2746
2747
    // Confirm that the existing node still has the correct field value.
2748
    $this->drupalGet("node/{$node->nid}");
2749
    $this->assertText($value, 'The original field value is visible to an administrator.');
2750
2751
    // Confirm that the new default value appears when creating a new node.
2752
    $this->drupalGet('node/add/page');
2753
    $this->assertRaw($default, 'The updated default value is displayed when creating a new node.');
2754
  }
2755
}
2756
2757
/**
2758
 * Tests changing view modes for nodes.
2759
 */
2760
class NodeEntityViewModeAlterTest extends NodeWebTestCase {
2761
2762
  public static function getInfo() {
2763
    return array(
2764
      'name' => 'Node entity view mode',
2765
      'description' => 'Test changing view mode.',
2766
      'group' => 'Node'
2767
    );
2768
  }
2769
2770
  function setUp() {
2771
    parent::setUp(array('node_test'));
2772
  }
2773
2774
  /**
2775
   * Create a "Basic page" node and verify its consistency in the database.
2776
   */
2777
  function testNodeViewModeChange() {
2778
    $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
2779
    $this->drupalLogin($web_user);
2780
2781
    // Create a node.
2782
    $edit = array();
2783
    $langcode = LANGUAGE_NONE;
2784
    $edit["title"] = $this->randomName(8);
2785 b4adf10d Assos Assos
    $edit["body[$langcode][0][value]"] = 'Data that should appear only in the body for the node.';
2786
    $edit["body[$langcode][0][summary]"] = 'Extra data that should appear only in the teaser for the node.';
2787 85ad3d82 Assos Assos
    $this->drupalPost('node/add/page', $edit, t('Save'));
2788
2789
    $node = $this->drupalGetNodeByTitle($edit["title"]);
2790
2791
    // Set the flag to alter the view mode and view the node.
2792
    variable_set('node_test_change_view_mode', 'teaser');
2793
    $this->drupalGet('node/' . $node->nid);
2794
2795
    // Check that teaser mode is viewed.
2796
    $this->assertText('Extra data that should appear only in the teaser for the node.', 'Teaser text present');
2797
    // Make sure body text is not present.
2798
    $this->assertNoText('Data that should appear only in the body for the node.', 'Body text not present');
2799
2800 b4adf10d Assos Assos
    // Test that the correct build mode has been set.
2801
    $build = node_view($node);
2802
    $this->assertEqual($build['#view_mode'], 'teaser', 'The view mode has correctly been set to teaser.');
2803
  }
2804
2805
  /**
2806
   * Tests fields that were previously hidden when the view mode is changed.
2807
   */
2808
  function testNodeViewModeChangeHiddenField() {
2809
    // Hide the tags field on the default display
2810
    $instance = field_info_instance('node', 'field_tags', 'article');
2811
    $instance['display']['default']['type'] = 'hidden';
2812
    field_update_instance($instance);
2813
2814
    $web_user = $this->drupalCreateUser(array('create article content', 'edit own article content'));
2815
    $this->drupalLogin($web_user);
2816
2817
    // Create a node.
2818
    $edit = array();
2819
    $langcode = LANGUAGE_NONE;
2820
    $edit["title"] = $this->randomName(8);
2821
    $edit["body[$langcode][0][value]"] = 'Data that should appear only in the body for the node.';
2822
    $edit["body[$langcode][0][summary]"] = 'Extra data that should appear only in the teaser for the node.';
2823
    $edit["field_tags[$langcode]"] = 'Extra tag';
2824
    $this->drupalPost('node/add/article', $edit, t('Save'));
2825
2826
    $node = $this->drupalGetNodeByTitle($edit["title"]);
2827
2828
    // Set the flag to alter the view mode and view the node.
2829
    variable_set('node_test_change_view_mode', 'teaser');
2830
    $this->drupalGet('node/' . $node->nid);
2831
2832
    // Check that teaser mode is viewed.
2833
    $this->assertText('Extra data that should appear only in the teaser for the node.', 'Teaser text present');
2834
    // Make sure body text is not present.
2835
    $this->assertNoText('Data that should appear only in the body for the node.', 'Body text not present');
2836
    // Make sure tags are present.
2837
    $this->assertText('Extra tag', 'Taxonomy term present');
2838
2839 85ad3d82 Assos Assos
    // Test that the correct build mode has been set.
2840
    $build = node_view($node);
2841
    $this->assertEqual($build['#view_mode'], 'teaser', 'The view mode has correctly been set to teaser.');
2842
  }
2843
}
2844
2845
/**
2846
 * Tests the cache invalidation of node operations.
2847
 */
2848
class NodePageCacheTest extends NodeWebTestCase {
2849
2850
  /**
2851
   * An admin user with administrative permissions for nodes.
2852
   */
2853
  protected $admin_user;
2854
2855
  public static function getInfo() {
2856
    return array(
2857
        'name' => 'Node page cache test',
2858
        'description' => 'Test cache invalidation of node operations.',
2859
        'group' => 'Node',
2860
    );
2861
  }
2862
2863
  function setUp() {
2864
    parent::setUp();
2865
2866
    variable_set('cache', 1);
2867
    variable_set('page_cache_maximum_age', 300);
2868
2869
    $this->admin_user = $this->drupalCreateUser(array(
2870
        'bypass node access',
2871
        'access content overview',
2872
        'administer nodes',
2873
    ));
2874
  }
2875
2876
  /**
2877
   * Tests deleting nodes clears page cache.
2878
   */
2879
  public function testNodeDelete() {
2880
    $node_path = 'node/' . $this->drupalCreateNode()->nid;
2881
2882
    // Populate page cache.
2883
    $this->drupalGet($node_path);
2884
2885
    // Login and delete the node.
2886
    $this->drupalLogin($this->admin_user);
2887
    $this->drupalPost($node_path . '/delete', array(), t('Delete'));
2888
2889
    // Logout and check the node is not available.
2890
    $this->drupalLogout();
2891
    $this->drupalGet($node_path);
2892
    $this->assertResponse(404);
2893
2894
    // Create two new nodes.
2895
    $nodes[0] = $this->drupalCreateNode();
2896
    $nodes[1] = $this->drupalCreateNode();
2897
    $node_path = 'node/' . $nodes[0]->nid;
2898
2899
    // Populate page cache.
2900
    $this->drupalGet($node_path);
2901
2902
    // Login and delete the nodes.
2903
    $this->drupalLogin($this->admin_user);
2904
    $this->drupalGet('admin/content');
2905
    $edit = array(
2906
        'operation' => 'delete',
2907
        'nodes[' . $nodes[0]->nid . ']' => TRUE,
2908
        'nodes[' . $nodes[1]->nid . ']' => TRUE,
2909
    );
2910
    $this->drupalPost(NULL, $edit, t('Update'));
2911
    $this->drupalPost(NULL, array(), t('Delete'));
2912
2913
    // Logout and check the node is not available.
2914
    $this->drupalLogout();
2915
    $this->drupalGet($node_path);
2916
    $this->assertResponse(404);
2917
  }
2918
}