summaryrefslogtreecommitdiffstats
path: root/modules/node/node.test
blob: d789d3c0e654ad61287a0bbb42709981c6f3f28b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
<?php

/**
 * @file
 * Tests for node.module.
 */

/**
 * Defines a base class for testing the Node module.
 */
class NodeWebTestCase extends DrupalWebTestCase {
  function setUp() {
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'node';
    parent::setUp($modules);

    // Create Basic page and Article node types.
    if ($this->profile != 'standard') {
      $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page'));
      $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
    }
  }
}

/**
 * Test the node_load_multiple() function.
 */
class NodeLoadMultipleTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Load multiple nodes',
      'description' => 'Test the loading of multiple nodes.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();
    $web_user = $this->drupalCreateUser(array('create article content', 'create page content'));
    $this->drupalLogin($web_user);
  }

  /**
   * Create four nodes and ensure they're loaded correctly.
   */
  function testNodeMultipleLoad() {
    $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
    $node2 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
    $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 0));
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0));

    // Confirm that promoted nodes appear in the default node listing.
    $this->drupalGet('node');
    $this->assertText($node1->title, t('Node title appears on the default listing.'));
    $this->assertText($node2->title, t('Node title appears on the default listing.'));
    $this->assertNoText($node3->title, t('Node title does not appear in the default listing.'));
    $this->assertNoText($node4->title, t('Node title does not appear in the default listing.'));

    // Load nodes with only a condition. Nodes 3 and 4 will be loaded.
    $nodes = node_load_multiple(NULL, array('promote' => 0));
    $this->assertEqual($node3->title, $nodes[$node3->nid]->title, t('Node was loaded.'));
    $this->assertEqual($node4->title, $nodes[$node4->nid]->title, t('Node was loaded.'));
    $count = count($nodes);
    $this->assertTrue($count == 2, t('@count nodes loaded.', array('@count' => $count)));

    // Load nodes by nid. Nodes 1, 2 and 4 will be loaded.
    $nodes = node_load_multiple(array(1, 2, 4));
    $count = count($nodes);
    $this->assertTrue(count($nodes) == 3, t('@count nodes loaded', array('@count' => $count)));
    $this->assertTrue(isset($nodes[$node1->nid]), t('Node is correctly keyed in the array'));
    $this->assertTrue(isset($nodes[$node2->nid]), t('Node is correctly keyed in the array'));
    $this->assertTrue(isset($nodes[$node4->nid]), t('Node is correctly keyed in the array'));
    foreach ($nodes as $node) {
      $this->assertTrue(is_object($node), t('Node is an object'));
    }

    // Load nodes by nid, where type = article. Nodes 1, 2 and 3 will be loaded.
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article'));
    $count = count($nodes);
    $this->assertTrue($count == 3, t('@count nodes loaded', array('@count' => $count)));
    $this->assertEqual($nodes[$node1->nid]->title, $node1->title, t('Node successfully loaded.'));
    $this->assertEqual($nodes[$node2->nid]->title, $node2->title, t('Node successfully loaded.'));
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, t('Node successfully loaded.'));
    $this->assertFalse(isset($nodes[$node4->nid]));

    // Now that all nodes have been loaded into the static cache, ensure that
    // they are loaded correctly again when a condition is passed.
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article'));
    $count = count($nodes);
    $this->assertTrue($count == 3, t('@count nodes loaded.', array('@count' => $count)));
    $this->assertEqual($nodes[$node1->nid]->title, $node1->title, t('Node successfully loaded'));
    $this->assertEqual($nodes[$node2->nid]->title, $node2->title, t('Node successfully loaded'));
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, t('Node successfully loaded'));
    $this->assertFalse(isset($nodes[$node4->nid]), t('Node was not loaded'));

    // Load nodes by nid, where type = article and promote = 0.
    $nodes = node_load_multiple(array(1, 2, 3, 4), array('type' => 'article', 'promote' => 0));
    $count = count($nodes);
    $this->assertTrue($count == 1, t('@count node loaded', array('@count' => $count)));
    $this->assertEqual($nodes[$node3->nid]->title, $node3->title, t('Node successfully loaded.'));
  }
}

/**
 * Tests for the hooks invoked during node_load().
 */
class NodeLoadHooksTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node load hooks',
      'description' => 'Test the hooks invoked when a node is being loaded.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp('node_test');
  }

  /**
   * Test that hook_node_load() is invoked correctly.
   */
  function testHookNodeLoad() {
    // Create some sample articles and pages.
    $node1 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_PUBLISHED));
    $node2 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_PUBLISHED));
    $node3 = $this->drupalCreateNode(array('type' => 'article', 'status' => NODE_NOT_PUBLISHED));
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'status' => NODE_NOT_PUBLISHED));

    // Check that when a set of nodes that only contains articles is loaded,
    // the properties added to the node by node_test_load_node() correctly
    // reflect the expected values.
    $nodes = node_load_multiple(array(), array('status' => NODE_PUBLISHED));
    $loaded_node = end($nodes);
    $this->assertEqual($loaded_node->node_test_loaded_nids, array($node1->nid, $node2->nid), t('hook_node_load() received the correct list of node IDs the first time it was called.'));
    $this->assertEqual($loaded_node->node_test_loaded_types, array('article'), t('hook_node_load() received the correct list of node types the first time it was called.'));

    // Now, as part of the same page request, load a set of nodes that contain
    // both articles and pages, and make sure the parameters passed to
    // node_test_node_load() are correctly updated.
    $nodes = node_load_multiple(array(), array('status' => NODE_NOT_PUBLISHED));
    $loaded_node = end($nodes);
    $this->assertEqual($loaded_node->node_test_loaded_nids, array($node3->nid, $node4->nid), t('hook_node_load() received the correct list of node IDs the second time it was called.'));
    $this->assertEqual($loaded_node->node_test_loaded_types, array('article', 'page'), t('hook_node_load() received the correct list of node types the second time it was called.'));
  }
}

class NodeRevisionsTestCase extends DrupalWebTestCase {
  protected $nodes;
  protected $logs;

  public static function getInfo() {
    return array(
      'name' => 'Node revisions',
      'description' => 'Create a node with revisions and test viewing, saving, reverting, and deleting revisions.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    // Create and login user.
    $web_user = $this->drupalCreateUser(array('view revisions', 'revert revisions', 'edit any page content',
                                               'delete revisions', 'delete any page content'));
    $this->drupalLogin($web_user);

    // Create initial node.
    $node = $this->drupalCreateNode();
    $settings = get_object_vars($node);
    $settings['revision'] = 1;

    $nodes = array();
    $logs = array();

    // Get original node.
    $nodes[] = $node;

    // Create three revisions.
    $revision_count = 3;
    for ($i = 0; $i < $revision_count; $i++) {
      $logs[] = $settings['log'] = $this->randomName(32);

      // Create revision with random title and body and update variables.
      $this->drupalCreateNode($settings);
      $node = node_load($node->nid); // Make sure we get revision information.
      $settings = get_object_vars($node);

      $nodes[] = $node;
    }

    $this->nodes = $nodes;
    $this->logs = $logs;
  }

  /**
   * Check node revision related operations.
   */
  function testRevisions() {
    $nodes = $this->nodes;
    $logs = $this->logs;

    // Get last node for simple checks.
    $node = $nodes[3];

    // Confirm the correct revision text appears on "view revisions" page.
    $this->drupalGet("node/$node->nid/revisions/$node->vid/view");
    $this->assertText($node->body[LANGUAGE_NONE][0]['value'], t('Correct text displays for version.'));

    // Confirm the correct log message appears on "revisions overview" page.
    $this->drupalGet("node/$node->nid/revisions");
    foreach ($logs as $log) {
      $this->assertText($log, t('Log message found.'));
    }

    // Confirm that revisions revert properly.
    $this->drupalPost("node/$node->nid/revisions/{$nodes[1]->vid}/revert", array(), t('Revert'));
    $this->assertRaw(t('@type %title has been reverted back to the revision from %revision-date.',
                        array('@type' => 'Basic page', '%title' => $nodes[1]->title,
                              '%revision-date' => format_date($nodes[1]->revision_timestamp))), t('Revision reverted.'));
    $reverted_node = node_load($node->nid);
    $this->assertTrue(($nodes[1]->body[LANGUAGE_NONE][0]['value'] == $reverted_node->body[LANGUAGE_NONE][0]['value']), t('Node reverted correctly.'));

    // Confirm revisions delete properly.
    $this->drupalPost("node/$node->nid/revisions/{$nodes[1]->vid}/delete", array(), t('Delete'));
    $this->assertRaw(t('Revision from %revision-date of @type %title has been deleted.',
                        array('%revision-date' => format_date($nodes[1]->revision_timestamp),
                              '@type' => 'Basic page', '%title' => $nodes[1]->title)), t('Revision deleted.'));
    $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, t('Revision not found.'));
  }

  /**
   * Checks that revisions are correctly saved without log messages.
   */
  function testNodeRevisionWithoutLogMessage() {
    // Create a node with an initial log message.
    $log = $this->randomName(10);
    $node = $this->drupalCreateNode(array('log' => $log));

    // Save over the same revision and explicitly provide an empty log message
    // (for example, to mimic the case of a node form submitted with no text in
    // the "log message" field), and check that the original log message is
    // preserved.
    $new_title = $this->randomName(10) . 'testNodeRevisionWithoutLogMessage1';
    $updated_node = (object) array(
      'nid' => $node->nid,
      'vid' => $node->vid,
      'uid' => $node->uid,
      'type' => $node->type,
      'title' => $new_title,
      'log' => '',
    );
    node_save($updated_node);
    $this->drupalGet('node/' . $node->nid);
    $this->assertText($new_title, t('New node title appears on the page.'));
    $node_revision = node_load($node->nid, NULL, TRUE);
    $this->assertEqual($node_revision->log, $log, t('After an existing node revision is re-saved without a log message, the original log message is preserved.'));

    // Create another node with an initial log message.
    $node = $this->drupalCreateNode(array('log' => $log));

    // Save a new node revision without providing a log message, and check that
    // this revision has an empty log message.
    $new_title = $this->randomName(10) . 'testNodeRevisionWithoutLogMessage2';
    $updated_node = (object) array(
      'nid' => $node->nid,
      'vid' => $node->vid,
      'uid' => $node->uid,
      'type' => $node->type,
      'title' => $new_title,
      'revision' => 1,
    );
    node_save($updated_node);
    $this->drupalGet('node/' . $node->nid);
    $this->assertText($new_title, 'New node title appears on the page.');
    $node_revision = node_load($node->nid, NULL, TRUE);
    $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.');
  }
}

class PageEditTestCase extends DrupalWebTestCase {
  protected $web_user;
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Node edit',
      'description' => 'Create a node and test node edit functionality.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    $this->web_user = $this->drupalCreateUser(array('edit own page content', 'create page content'));
    $this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes'));
  }

  /**
   * Check node edit functionality.
   */
  function testPageEdit() {
    $this->drupalLogin($this->web_user);

    $langcode = LANGUAGE_NONE;
    $title_key = "title";
    $body_key = "body[$langcode][0][value]";
    // Create node to edit.
    $edit = array();
    $edit[$title_key] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check that the node exists in the database.
    $node = $this->drupalGetNodeByTitle($edit[$title_key]);
    $this->assertTrue($node, t('Node found in database.'));

    // Check that "edit" link points to correct page.
    $this->clickLink(t('Edit'));
    $edit_url = url("node/$node->nid/edit", array('absolute' => TRUE));
    $actual_url = $this->getURL();
    $this->assertEqual($edit_url, $actual_url, t('On edit page.'));

    // Check that the title and body fields are displayed with the correct values.
    $active = '<span class="element-invisible">' . t('(active tab)') . '</span>';
    $link_text = t('!local-task-title!active', array('!local-task-title' => t('Edit'), '!active' => $active));
    $this->assertText(strip_tags($link_text), 0, t('Edit tab found and marked active.'));
    $this->assertFieldByName($title_key, $edit[$title_key], t('Title field displayed.'));
    $this->assertFieldByName($body_key, $edit[$body_key], t('Body field displayed.'));

    // Edit the content of the node.
    $edit = array();
    $edit[$title_key] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    // Stay on the current page, without reloading.
    $this->drupalPost(NULL, $edit, t('Save'));

    // Check that the title and body fields are displayed with the updated values.
    $this->assertText($edit[$title_key], t('Title displayed.'));
    $this->assertText($edit[$body_key], t('Body displayed.'));

    // Login as a second administrator user.
    $second_web_user = $this->drupalCreateUser(array('administer nodes', 'edit any page content'));
    $this->drupalLogin($second_web_user);
    // Edit the same node, creating a new revision.
    $this->drupalGet("node/$node->nid/edit");
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    $edit['revision'] = TRUE;
    $this->drupalPost(NULL, $edit, t('Save'));

    // Ensure that the node revision has been created.
    $revised_node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertNotIdentical($node->vid, $revised_node->vid, 'A new revision has been created.');
    // Ensure that the node author is preserved when it was not changed in the
    // edit form.
    $this->assertIdentical($node->uid, $revised_node->uid, 'The node author has been preserved.');
    // Ensure that the revision authors are different since the revisions were
    // made by different users.
    $first_node_version = node_load($node->nid, $node->vid);
    $second_node_version = node_load($node->nid, $revised_node->vid);
    $this->assertNotIdentical($first_node_version->revision_uid, $second_node_version->revision_uid, 'Each revision has a distinct user.');
  }

  /**
   * Check changing node authored by fields.
   */
  function testPageAuthoredBy() {
    $this->drupalLogin($this->admin_user);

    // Create node to edit.
    $langcode = LANGUAGE_NONE;
    $body_key = "body[$langcode][0][value]";
    $edit = array();
    $edit['title'] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check that the node was authored by the currently logged in user.
    $node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertIdentical($node->uid, $this->admin_user->uid, 'Node authored by admin user.');

    // Try to change the 'authored by' field to an invalid user name.
    $edit = array(
      'name' => 'invalid-name',
    );
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
    $this->assertText('The username invalid-name does not exist.');

    // Change the authored by field to an empty string, which should assign
    // authorship to the anonymous user (uid 0).
    $edit['name'] = '';
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
    $node = node_load($node->nid, NULL, TRUE);
    $this->assertIdentical($node->uid, '0', 'Node authored by anonymous user.');

    // Change the authored by field to another user's name (that is not
    // logged in).
    $edit['name'] = $this->web_user->name;
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
    $node = node_load($node->nid, NULL, TRUE);
    $this->assertIdentical($node->uid, $this->web_user->uid, 'Node authored by normal user.');

    // Check that normal users cannot change the authored by information.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('node/' . $node->nid . '/edit');
    $this->assertNoFieldByName('name');
  }
}

class PagePreviewTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node preview',
      'description' => 'Test node preview functionality.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    $web_user = $this->drupalCreateUser(array('edit own page content', 'create page content'));
    $this->drupalLogin($web_user);
  }

  /**
   * Check the node preview functionality.
   */
  function testPagePreview() {
    $langcode = LANGUAGE_NONE;
    $title_key = "title";
    $body_key = "body[$langcode][0][value]";

    // Fill in node creation form and preview node.
    $edit = array();
    $edit[$title_key] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Preview'));

    // Check that the preview is displaying the title and body.
    $this->assertTitle(t('Preview | Drupal'), t('Basic page title is preview.'));
    $this->assertText($edit[$title_key], t('Title displayed.'));
    $this->assertText($edit[$body_key], t('Body displayed.'));

    // Check that the title and body fields are displayed with the correct values.
    $this->assertFieldByName($title_key, $edit[$title_key], t('Title field displayed.'));
    $this->assertFieldByName($body_key, $edit[$body_key], t('Body field displayed.'));
  }

  /**
   * Check the node preview functionality, when using revisions.
   */
  function testPagePreviewWithRevisions() {
    $langcode = LANGUAGE_NONE;
    $title_key = "title";
    $body_key = "body[$langcode][0][value]";
    // Force revision on "Basic page" content.
    variable_set('node_options_page', array('status', 'revision'));

    // Fill in node creation form and preview node.
    $edit = array();
    $edit[$title_key] = $this->randomName(8);
    $edit[$body_key] = $this->randomName(16);
    $edit['log'] = $this->randomName(32);
    $this->drupalPost('node/add/page', $edit, t('Preview'));

    // Check that the preview is displaying the title and body.
    $this->assertTitle(t('Preview | Drupal'), t('Basic page title is preview.'));
    $this->assertText($edit[$title_key], t('Title displayed.'));
    $this->assertText($edit[$body_key], t('Body displayed.'));

    // Check that the title and body fields are displayed with the correct values.
    $this->assertFieldByName($title_key, $edit[$title_key], t('Title field displayed.'));
    $this->assertFieldByName($body_key, $edit[$body_key], t('Body field displayed.'));

    // Check that the log field has the correct value.
    $this->assertFieldByName('log', $edit['log'], t('Log field displayed.'));
  }
}

class NodeCreationTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node creation',
      'description' => 'Create a node and test saving it.',
      'group' => 'Node',
    );
  }

  function setUp() {
    // Enable dummy module that implements hook_node_insert for exceptions.
    parent::setUp('node_test_exception');

    $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
    $this->drupalLogin($web_user);
  }

  /**
   * Create a "Basic page" node and verify its consistency in the database.
   */
  function testNodeCreation() {
    // Create a node.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName(8);
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check that the Basic page has been created.
    $this->assertRaw(t('!post %title has been created.', array('!post' => 'Basic page', '%title' => $edit["title"])), t('Basic page created.'));

    // Check that the node exists in the database.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $this->assertTrue($node, t('Node found in database.'));
  }

  /**
   * Create a page node and verify that a transaction rolls back the failed creation
   */
  function testFailedPageCreation() {
    // Create a node.
    $edit = array(
      'uid'      => $this->loggedInUser->uid,
      'name'     => $this->loggedInUser->name,
      'type'     => 'page',
      'language' => LANGUAGE_NONE,
      'title'    => 'testing_transaction_exception',
    );

    try {
      node_save((object) $edit);
      $this->fail(t('Expected exception has not been thrown.'));
    }
    catch (Exception $e) {
      $this->pass(t('Expected exception has been thrown.'));
    }

    if (Database::getConnection()->supportsTransactions()) {
      // Check that the node does not exist in the database.
      $node = $this->drupalGetNodeByTitle($edit['title']);
      $this->assertFalse($node, t('Transactions supported, and node not found in database.'));
    }
    else {
      // Check that the node exists in the database.
      $node = $this->drupalGetNodeByTitle($edit['title']);
      $this->assertTrue($node, t('Transactions not supported, and node found in database.'));

      // Check that the failed rollback was logged.
      $records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
      $this->assertTrue(count($records) > 0, t('Transactions not supported, and rollback error logged to watchdog.'));
    }

    // Check that the rollback error was logged.
    $records = db_query("SELECT wid FROM {watchdog} WHERE variables LIKE '%Test exception for rollback.%'")->fetchAll();
    $this->assertTrue(count($records) > 0, t('Rollback explanatory error logged to watchdog.'));
  }
}

class PageViewTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node edit permissions',
      'description' => 'Create a node and test edit permissions.',
      'group' => 'Node',
    );
  }

  /**
   * Creates a node and then an anonymous and unpermissioned user attempt to edit the node.
   */
  function testPageView() {
    // Create a node to view.
    $node = $this->drupalCreateNode();
    $this->assertTrue(node_load($node->nid), t('Node created.'));

    // Try to edit with anonymous user.
    $html = $this->drupalGet("node/$node->nid/edit");
    $this->assertResponse(403);

    // Create a user without permission to edit node.
    $web_user = $this->drupalCreateUser(array('access content'));
    $this->drupalLogin($web_user);

    // Attempt to access edit page.
    $this->drupalGet("node/$node->nid/edit");
    $this->assertResponse(403);

    // Create user with permission to edit node.
    $web_user = $this->drupalCreateUser(array('bypass node access'));
    $this->drupalLogin($web_user);

    // Attempt to access edit page.
    $this->drupalGet("node/$node->nid/edit");
    $this->assertResponse(200);
  }
}

class SummaryLengthTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Summary length',
      'description' => 'Test summary length.',
      'group' => 'Node',
    );
  }

  /**
   * Creates a node and then an anonymous and unpermissioned user attempt to edit the node.
   */
  function testSummaryLength() {
    // Create a node to view.
    $settings = array(
      '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.'))),
      'promote' => 1,
    );
    $node = $this->drupalCreateNode($settings);
    $this->assertTrue(node_load($node->nid), t('Node created.'));

    // Create user with permission to view the node.
    $web_user = $this->drupalCreateUser(array('access content', 'administer content types'));
    $this->drupalLogin($web_user);

    // Attempt to access the front page.
    $this->drupalGet("node");
    // The node teaser when it has 600 characters in length
    $expected = 'What is a Drupalism?';
    $this->assertRaw($expected, t('Check that the summary is 600 characters in length'), 'Node');

    // Change the teaser length for "Basic page" content type.
    $instance = field_info_instance('node', 'body', $node->type);
    $instance['display']['teaser']['settings']['trim_length'] = 200;
    field_update_instance($instance);

    // Attempt to access the front page again and check if the summary is now only 200 characters in length.
    $this->drupalGet("node");
    $this->assertNoRaw($expected, t('Check that the summary is not longer than 200 characters'), 'Node');
  }
}

class NodeTitleXSSTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node title XSS filtering',
      'description' => 'Create a node with dangerous tags in its title and test that they are escaped.',
      'group' => 'Node',
    );
  }

  function testNodeTitleXSS() {
    // Prepare a user to do the stuff.
    $web_user = $this->drupalCreateUser(array('create page content', 'edit any page content'));
    $this->drupalLogin($web_user);

    $xss = '<script>alert("xss")</script>';
    $title = $xss . $this->randomName();
    $edit = array("title" => $title);

    $this->drupalPost('node/add/page', $edit, t('Preview'));
    $this->assertNoRaw($xss, t('Harmful tags are escaped when previewing a node.'));

    $settings = array('title' => $title);
    $node = $this->drupalCreateNode($settings);

    $this->drupalGet('node/' . $node->nid);
    // assertTitle() decodes HTML-entities inside the <title> element.
    $this->assertTitle($edit["title"] . ' | Drupal', t('Title is diplayed when viewing a node.'));
    $this->assertNoRaw($xss, t('Harmful tags are escaped when viewing a node.'));

    $this->drupalGet('node/' . $node->nid . '/edit');
    $this->assertNoRaw($xss, t('Harmful tags are escaped when editing a node.'));
  }
}

class NodeBlockTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Block availability',
      'description' => 'Check if the syndicate block is available.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    // Create and login user
    $admin_user = $this->drupalCreateUser(array('administer blocks'));
    $this->drupalLogin($admin_user);
  }

  function testSyndicateBlock() {
    // Set block title to confirm that the interface is available.
    $this->drupalPost('admin/structure/block/manage/node/syndicate/configure', array('title' => $this->randomName(8)), t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));

    // Set the block to a region to confirm block is available.
    $edit = array();
    $edit['blocks[node_syndicate][region]'] = 'footer';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->assertText(t('The block settings have been updated.'), t('Block successfully move to footer region.'));
  }
}

/**
 * Check that the post information displays when enabled for a content type.
 */
class NodePostSettingsTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node post information display',
      'description' => 'Check that the post information (submitted by Username on date) text displays appropriately.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    $web_user = $this->drupalCreateUser(array('create page content', 'administer content types', 'access user profiles'));
    $this->drupalLogin($web_user);
  }

  /**
   * Set "Basic page" content type to display post information and confirm its presence on a new node.
   */
  function testPagePostInfo() {

    // Set "Basic page" content type to display post information.
    $edit = array();
    $edit['node_submitted'] = TRUE;
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));

    // Create a node.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName(8);
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check that the post information is displayed.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $elements = $this->xpath('//div[contains(@class,:class)]', array(':class' => 'submitted'));
    $this->assertEqual(count($elements), 1, t('Post information is displayed.'));
  }

  /**
   * Set "Basic page" content type to not display post information and confirm its absence on a new node.
   */
  function testPageNotPostInfo() {

    // Set "Basic page" content type to display post information.
    $edit = array();
    $edit['node_submitted'] = FALSE;
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));

    // Create a node.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName(8);
    $edit["body[$langcode][0][value]"] = $this->randomName(16);
    $this->drupalPost('node/add/page', $edit, t('Save'));

    // Check that the post information is displayed.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $this->assertNoRaw('<span class="submitted">', t('Post information is not displayed.'));
  }
}

/**
 * Ensure that data added to nodes by other modules appears in RSS feeds.
 *
 * Create a node, enable the node_test module to ensure that extra data is
 * added to the node->content array, then verify that the data appears on the
 * sitewide RSS feed at rss.xml.
 */
class NodeRSSContentTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node RSS Content',
      'description' => 'Ensure that data added to nodes by other modules appears in RSS feeds.',
      'group' => 'Node',
    );
  }

  function setUp() {
    // Enable dummy module that implements hook_node_view.
    parent::setUp('node_test');

    // Use bypass node access permission here, because the test class uses
    // hook_grants_alter() to deny access to everyone on node_access
    // queries.
    $user = $this->drupalCreateUser(array('bypass node access', 'access content', 'create article content'));
    $this->drupalLogin($user);
  }

  /**
   * Create a new node and ensure that it includes the custom data when added
   * to an RSS feed.
   */
  function testNodeRSSContent() {
    // Create a node.
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));

    $this->drupalGet('rss.xml');

    // Check that content added in 'rss' view mode appear in RSS feed.
    $rss_only_content = t('Extra data that should appear only in the RSS feed for node !nid.', array('!nid' => $node->nid));
    $this->assertText($rss_only_content, t('Node content designated for RSS appear in RSS feed.'));

    // Check that content added in view modes other than 'rss' doesn't
    // appear in RSS feed.
    $non_rss_content = t('Extra data that should appear everywhere except the RSS feed for node !nid.', array('!nid' => $node->nid));
    $this->assertNoText($non_rss_content, t('Node content not designed for RSS doesn\'t appear in RSS feed.'));

    // Check that extra RSS elements and namespaces are added to RSS feed.
    $test_element = array(
      'key' => 'testElement',
      'value' => t('Value of testElement RSS element for node !nid.', array('!nid' => $node->nid)),
    );
    $test_ns = 'xmlns:drupaltest="http://example.com/test-namespace"';
    $this->assertRaw(format_xml_elements(array($test_element)), t('Extra RSS elements appear in RSS feed.'));
    $this->assertRaw($test_ns, t('Extra namespaces appear in RSS feed.'));

    // Check that content added in 'rss' view mode doesn't appear when
    // viewing node.
    $this->drupalGet("node/$node->nid");
    $this->assertNoText($rss_only_content, t('Node content designed for RSS doesn\'t appear when viewing node.'));
    
    // Check that the node feed page does not try to interpret additional path
    // components as arguments for node_feed() and returns default content.
    $this->drupalGet('rss.xml/' . $this->randomName() . '/' . $this->randomName());
    $this->assertText($rss_only_content, t('Ignore page arguments when delivering rss.xml.'));
  }
}

/**
 * Test case to verify basic node_access functionality.
 * @todo Cover hook_node_access in a separate test class.
 * hook_node_access_records is covered in another test class.
 */
class NodeAccessTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node access',
      'description' => 'Test node_access function',
      'group' => 'Node',
    );
  }

  /**
   * Asserts node_access correctly grants or denies access.
   */
  function assertNodeAccess($ops, $node, $account) {
    foreach ($ops as $op => $result) {
      $msg = t("node_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
      $this->assertEqual($result, node_access($op, $node, $account), $msg);
    }
  }

  function setUp() {
    parent::setUp();
    // Clear permissions for authenticated users.
    db_delete('role_permission')
      ->condition('rid', DRUPAL_AUTHENTICATED_RID)
      ->execute();
  }

  /**
   * Runs basic tests for node_access function.
   */
  function testNodeAccess() {
    // Ensures user without 'access content' permission can do nothing.
    $web_user1 = $this->drupalCreateUser(array('create page content', 'edit any page content', 'delete any page content'));
    $node1 = $this->drupalCreateNode(array('type' => 'page'));
    $this->assertNodeAccess(array('create' => FALSE), 'page', $web_user1);
    $this->assertNodeAccess(array('view' => FALSE, 'update' => FALSE, 'delete' => FALSE), $node1, $web_user1);

    // Ensures user with 'bypass node access' permission can do everything.
    $web_user2 = $this->drupalCreateUser(array('bypass node access'));
    $node2 = $this->drupalCreateNode(array('type' => 'page'));
    $this->assertNodeAccess(array('create' => TRUE), 'page', $web_user2);
    $this->assertNodeAccess(array('view' => TRUE, 'update' => TRUE, 'delete' => TRUE), $node2, $web_user2);

    // User cannot 'view own unpublished content'.
    $web_user3 = $this->drupalCreateUser(array('access content'));
    $node3 = $this->drupalCreateNode(array('status' => 0, 'uid' => $web_user3->uid));
    $this->assertNodeAccess(array('view' => FALSE), $node3, $web_user3);

    // User cannot create content without permission.
    $this->assertNodeAccess(array('create' => FALSE), 'page', $web_user3);

    // User can 'view own unpublished content', but another user cannot.
    $web_user4 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
    $web_user5 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
    $node4 = $this->drupalCreateNode(array('status' => 0, 'uid' => $web_user4->uid));
    $this->assertNodeAccess(array('view' => TRUE, 'update' => FALSE), $node4, $web_user4);
    $this->assertNodeAccess(array('view' => FALSE), $node4, $web_user5);

    // Tests the default access provided for a published node.
    $node5 = $this->drupalCreateNode();
    $this->assertNodeAccess(array('view' => TRUE, 'update' => FALSE, 'delete' => FALSE), $node5, $web_user3);
  }
}

/**
 * Test case to verify hook_node_access_records functionality.
 */
class NodeAccessRecordsTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node access records',
      'description' => 'Test hook_node_access_records when acquiring grants.',
      'group' => 'Node',
    );
  }

  function setUp() {
    // Enable dummy module that implements hook_node_grants(),
    // hook_node_access_records(), hook_node_grants_alter() and
    // hook_node_access_records_alter().
    parent::setUp('node_test');
  }

  /**
   * Create a node and test the creation of node access rules.
   */
  function testNodeAccessRecords() {
    // Create an article node.
    $node1 = $this->drupalCreateNode(array('type' => 'article'));
    $this->assertTrue(node_load($node1->nid), t('Article node created.'));

    // Check to see if grants added by node_test_node_access_records made it in.
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node1->nid))->fetchAll();
    $this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
    $this->assertEqual($records[0]->realm, 'test_article_realm', t('Grant with article_realm acquired for node without alteration.'));
    $this->assertEqual($records[0]->gid, 1, t('Grant with gid = 1 acquired for node without alteration.'));

    // Create an unpromoted "Basic page" node.
    $node2 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0));
    $this->assertTrue(node_load($node2->nid), t('Unpromoted basic page node created.'));

    // Check to see if grants added by node_test_node_access_records made it in.
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node2->nid))->fetchAll();
    $this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
    $this->assertEqual($records[0]->realm, 'test_page_realm', t('Grant with page_realm acquired for node without alteration.'));
    $this->assertEqual($records[0]->gid, 1, t('Grant with gid = 1 acquired for node without alteration.'));

    // Create an unpromoted, unpublished "Basic page" node.
    $node3 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0, 'status' => 0));
    $this->assertTrue(node_load($node3->nid), t('Unpromoted, unpublished basic page node created.'));

    // Check to see if grants added by node_test_node_access_records made it in.
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node3->nid))->fetchAll();
    $this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
    $this->assertEqual($records[0]->realm, 'test_page_realm', t('Grant with page_realm acquired for node without alteration.'));
    $this->assertEqual($records[0]->gid, 1, t('Grant with gid = 1 acquired for node without alteration.'));

    // Create a promoted "Basic page" node.
    $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 1));
    $this->assertTrue(node_load($node4->nid), t('Promoted basic page node created.'));

    // Check to see if grant added by node_test_node_access_records was altered
    // by node_test_node_access_records_alter.
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node4->nid))->fetchAll();
    $this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
    $this->assertEqual($records[0]->realm, 'test_alter_realm', t('Altered grant with alter_realm acquired for node.'));
    $this->assertEqual($records[0]->gid, 2, t('Altered grant with gid = 2 acquired for node.'));

    // Check to see if we can alter grants with hook_node_grants_alter().
    $operations = array('view', 'update', 'delete');
    // Create a user that is allowed to access content.
    $web_user = $this->drupalCreateUser(array('access content'));
    foreach ($operations as $op) {
      $grants = node_test_node_grants($op, $web_user);
      $altered_grants = $grants;
      drupal_alter('node_grants', $altered_grants, $web_user, $op);
      $this->assertNotEqual($grants, $altered_grants, t('Altered the %op grant for a user.', array('%op' => $op)));
    }

    // Check that core does not grant access to an unpublished node when an
    // empty $grants array is returned.
    $node6 = $this->drupalCreateNode(array('status' => 0, 'disable_node_access' => TRUE));
    $records = db_query('SELECT realm, gid FROM {node_access} WHERE nid = :nid', array(':nid' => $node6->nid))->fetchAll();
    $this->assertEqual(count($records), 0, t('Returned no records for unpublished node.'));
  }
}

/**
 * Tests for Node Access with a non-node base table.
 */
class NodeAccessBaseTableTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node Access on any table',
      'description' => 'Checks behavior of the node access subsystem if the base table is not node.',
      'group' => 'Node',
    );
  }

  /**
   * Enable modules and create user with specific permissions.
   */
  public function setUp() {
    parent::setUp('node_access_test');
    node_access_rebuild();
    variable_set('node_access_test_private', TRUE);
  }

  /**
   * Test the "private" node access.
   *
   * - Create 2 users with "access content" and "create article" permissions.
   * - Each user creates one private and one not private article.

   * - Test that each user can view the other user's non-private article.
   * - Test that each user cannot view the other user's private article.
   * - Test that each user finds only appropriate (non-private + own private)
   *   in taxonomy listing.
   * - Create another user with 'view any private content'.
   * - Test that user 4 can view all content created above.
   * - Test that user 4 can view all content on taxonomy listing.
   */
  function testNodeAccessBasic() {
    $num_simple_users = 2;
    $simple_users = array();

    // nodes keyed by uid and nid: $nodes[$uid][$nid] = $is_private;
    $this->nodesByUser = array();
    $titles = array(); // Titles keyed by nid
    $private_nodes = array(); // Array of nids marked private.
    for ($i = 0; $i < $num_simple_users; $i++) {
      $simple_users[$i] = $this->drupalCreateUser(array('access content', 'create article content'));
    }
    foreach ($simple_users as $this->webUser) {
      $this->drupalLogin($this->webUser);
      foreach (array(0 => 'Public', 1 => 'Private') as $is_private => $type) {
        $edit = array(
          'title' => t('@private_public Article created by @user', array('@private_public' => $type, '@user' => $this->webUser->name)),
        );
        if ($is_private) {
          $edit['private'] = TRUE;
          $edit['body[und][0][value]'] = 'private node';
          $edit['field_tags[und]'] = 'private';
        }
        else {
          $edit['body[und][0][value]'] = 'public node';
          $edit['field_tags[und]'] = 'public';
        }

        $this->drupalPost('node/add/article', $edit, t('Save'));
        $nid = db_query('SELECT nid FROM {node} WHERE title = :title', array(':title' => $edit['title']))->fetchField();
        $private_status = db_query('SELECT private FROM {node_access_test} where nid = :nid', array(':nid' => $nid))->fetchField();
        $this->assertTrue($is_private == $private_status, t('The private status of the node was properly set in the node_access_test table.'));
        if ($is_private) {
          $private_nodes[] = $nid;
        }
        $titles[$nid] = $edit['title'];
        $this->nodesByUser[$this->webUser->uid][$nid] = $is_private;
      }
    }
    $this->publicTid = db_query('SELECT tid FROM {taxonomy_term_data} WHERE name = :name', array(':name' => 'public'))->fetchField();
    $this->privateTid = db_query('SELECT tid FROM {taxonomy_term_data} WHERE name = :name', array(':name' => 'private'))->fetchField();
    $this->assertTrue($this->publicTid, t('Public tid was found'));
    $this->assertTrue($this->privateTid, t('Private tid was found'));
    foreach ($simple_users as $this->webUser) {
      $this->drupalLogin($this->webUser);
      // Check own nodes to see that all are readable.
      foreach ($this->nodesByUser as $uid => $data) {
        foreach ($data as $nid => $is_private) {
          $this->drupalGet('node/' . $nid);
          if ($is_private) {
            $should_be_visible = $uid == $this->webUser->uid;
          }
          else {
            $should_be_visible = TRUE;
          }
          $this->assertResponse($should_be_visible ? 200 : 403, strtr('A %private node by user %uid is %visible for user %current_uid.', array(
            '%private' => $is_private ? 'private' : 'public',
            '%uid' => $uid,
            '%visible' => $should_be_visible ? 'visible' : 'not visible',
            '%current_uid' => $this->webUser->uid,
          )));
        }
      }

      // Check to see that the correct nodes are shown on taxonomy/private
      // and taxonomy/public.
      $this->assertTaxonomyPage(FALSE);
    }

    // Now test that a user with 'access any private content' can view content.
    $access_user = $this->drupalCreateUser(array('access content', 'create article content', 'node test view', 'search content'));
    $this->drupalLogin($access_user);

    foreach ($this->nodesByUser as $uid => $private_status) {
      foreach ($private_status as $nid => $is_private) {
        $this->drupalGet('node/' . $nid);
        $this->assertResponse(200);
      }
    }

    // This user should be able to see all of the nodes on the relevant
    // taxonomy pages.
    $this->assertTaxonomyPage(TRUE);
  }

  /**
   * Checks taxonomy/term listings to ensure only accessible nodes are listed.
   *
   * @param $is_admin
   *   A boolean indicating whether the current user is an administrator. If
   *   TRUE, all nodes should be listed. If FALSE, only public nodes and the
   *   user's own private nodes should be listed.
   */
  protected function assertTaxonomyPage($is_admin) {
    foreach (array($this->publicTid, $this->privateTid) as $tid_is_private => $tid) {
      $this->drupalGet("taxonomy/term/$tid");
      $this->nids_visible = array();
      foreach ($this->xpath("//a[text()='Read more']") as $link) {
        $this->assertTrue(preg_match('|node/(\d+)$|', (string) $link['href'], $matches), 'Read more points to a node');
        $this->nids_visible[$matches[1]] = TRUE;
      }
      foreach ($this->nodesByUser as $uid => $data) {
        foreach ($data as $nid => $is_private) {
          // Private nodes should be visible on the private term page,
          // public nodes should be visible on the public term page.
          $should_be_visible = $tid_is_private == $is_private;
          // Non-administrators can only see their own nodes on the private
          // term page.
          if (!$is_admin && $tid_is_private) {
            $should_be_visible = $should_be_visible && $uid == $this->webUser->uid;
          }
          $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(
            '%private' => $is_private ? 'private' : 'public',
            '%uid' => $uid,
            '%visible' => isset($this->nids_visible[$nid]) ? 'visible' : 'not visible',
            '%current_uid' => $this->webUser->uid,
            '%tid_is_private' => $tid_is_private ? 'private' : 'public',
          )));
        }
      }
    }
  }
}

/**
 * Test case to check node save related functionality, including import-save
 */
class NodeSaveTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node save',
      'description' => 'Test node_save() for saving content.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp('node_test');
    // Create a user that is allowed to post; we'll use this to test the submission.
    $web_user = $this->drupalCreateUser(array('create article content'));
    $this->drupalLogin($web_user);
    $this->web_user = $web_user;
  }

  /**
   * Import test, to check if custom node ids are saved properly.
   * Workflow:
   *  - first create a piece of content
   *  - save the content
   *  - check if node exists
   */
  function testImport() {
    // Node ID must be a number that is not in the database.
    $max_nid = db_query('SELECT MAX(nid) FROM {node}')->fetchField();
    $test_nid = $max_nid + mt_rand(1000, 1000000);
    $title = $this->randomName(8);
    $node = array(
      'title' => $title,
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(32)))),
      'uid' => $this->web_user->uid,
      'type' => 'article',
      'nid' => $test_nid,
      'is_new' => TRUE,
    );
    $node = node_submit((object) $node);

    // Verify that node_submit did not overwrite the user ID.
    $this->assertEqual($node->uid, $this->web_user->uid, t('Function node_submit() preserves user ID'));

    node_save($node);
    // Test the import.
    $node_by_nid = node_load($test_nid);
    $this->assertTrue($node_by_nid, t('Node load by node ID.'));

    $node_by_title = $this->drupalGetNodeByTitle($title);
    $this->assertTrue($node_by_title, t('Node load by node title.'));
  }

  /**
   * Check that the "created" and "changed" timestamps are set correctly when
   * saving a new node or updating an existing node.
   */
  function testTimestamps() {
    // Use the default timestamps.
    $edit = array(
      'uid' => $this->web_user->uid,
      'type' => 'article',
      'title' => $this->randomName(8),
    );

    node_save((object) $edit);
    $node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertEqual($node->created, REQUEST_TIME, t('Creating a node sets default "created" timestamp.'));
    $this->assertEqual($node->changed, REQUEST_TIME, t('Creating a node sets default "changed" timestamp.'));

    // Store the timestamps.
    $created = $node->created;
    $changed = $node->changed;

    node_save($node);
    $node = $this->drupalGetNodeByTitle($edit['title'], TRUE);
    $this->assertEqual($node->created, $created, t('Updating a node preserves "created" timestamp.'));

    // Programmatically set the timestamps using hook_node_presave.
    $node->title = 'testing_node_presave';

    node_save($node);
    $node = $this->drupalGetNodeByTitle('testing_node_presave', TRUE);
    $this->assertEqual($node->created, 280299600, t('Saving a node uses "created" timestamp set in presave hook.'));
    $this->assertEqual($node->changed, 979534800, t('Saving a node uses "changed" timestamp set in presave hook.'));

    // Programmatically set the timestamps on the node.
    $edit = array(
      'uid' => $this->web_user->uid,
      'type' => 'article',
      'title' => $this->randomName(8),
      'created' => 280299600, // Sun, 19 Nov 1978 05:00:00 GMT
      'changed' => 979534800, // Drupal 1.0 release.
    );

    node_save((object) $edit);
    $node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertEqual($node->created, 280299600, t('Creating a node uses user-set "created" timestamp.'));
    $this->assertNotEqual($node->changed, 979534800, t('Creating a node doesn\'t use user-set "changed" timestamp.'));

    // Update the timestamps.
    $node->created = 979534800;
    $node->changed = 280299600;

    node_save($node);
    $node = $this->drupalGetNodeByTitle($edit['title'], TRUE);
    $this->assertEqual($node->created, 979534800, t('Updating a node uses user-set "created" timestamp.'));
    $this->assertNotEqual($node->changed, 280299600, t('Updating a node doesn\'t use user-set "changed" timestamp.'));
  }

  /**
   * Tests determing changes in hook_node_presave() and verifies the static node
   * load cache is cleared upon save.
   */
  function testDeterminingChanges() {
    // Initial creation.
    $node = (object) array(
      'uid' => $this->web_user->uid,
      'type' => 'article',
      'title' => 'test_changes',
    );
    node_save($node);

    // Update the node without applying changes.
    node_save($node);
    $this->assertEqual($node->title, 'test_changes', 'No changes have been determined.');

    // Apply changes.
    $node->title = 'updated';
    node_save($node);

    // The hook implementations node_test_node_presave() and
    // node_test_node_update() determine changes and change the title.
    $this->assertEqual($node->title, 'updated_presave_update', 'Changes have been determined.');

    // Test the static node load cache to be cleared.
    $node = node_load($node->nid);
    $this->assertEqual($node->title, 'updated_presave', 'Static cache has been cleared.');
  }
}

/**
 * Tests related to node types.
 */
class NodeTypeTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node types',
      'description' => 'Ensures that node type functions work correctly.',
      'group' => 'Node',
    );
  }

  /**
   * Ensure that node type functions (node_type_get_*) work correctly.
   *
   * Load available node types and validate the returned data.
   */
  function testNodeTypeGetFunctions() {
    $node_types = node_type_get_types();
    $node_names = node_type_get_names();

    $this->assertTrue(isset($node_types['article']), t('Node type article is available.'));
    $this->assertTrue(isset($node_types['page']), t('Node type basic page is available.'));

    $this->assertEqual($node_types['article']->name, $node_names['article'], t('Correct node type base has been returned.'));

    $this->assertEqual($node_types['article'], node_type_get_type('article'), t('Correct node type has been returned.'));
    $this->assertEqual($node_types['article']->name, node_type_get_name('article'), t('Correct node type name has been returned.'));
    $this->assertEqual($node_types['page']->base, node_type_get_base('page'), t('Correct node type base has been returned.'));
  }

  /**
   * Test creating a content type programmatically and via a form.
   */
  function testNodeTypeCreation() {
    // Create a content type programmaticaly.
    $type = $this->drupalCreateContentType();

    $type_exists = db_query('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => $type->type))->fetchField();
    $this->assertTrue($type_exists, 'The new content type has been created in the database.');

    // Login a test user.
    $web_user = $this->drupalCreateUser(array('create ' . $type->name . ' content'));
    $this->drupalLogin($web_user);

    $this->drupalGet('node/add/' . str_replace('_', '-', $type->name));
    $this->assertResponse(200, 'The new content type can be accessed at node/add.');

    // Create a content type via the user interface.
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types'));
    $this->drupalLogin($web_user);
    $edit = array(
      'name' => 'foo',
      'title_label' => 'title for foo',
      'type' => 'foo',
    );
    $this->drupalPost('admin/structure/types/add', $edit, t('Save content type'));
    $type_exists = db_query('SELECT 1 FROM {node_type} WHERE type = :type', array(':type' => 'foo'))->fetchField();
    $this->assertTrue($type_exists, 'The new content type has been created in the database.');
  }

  /**
   * Test editing a node type using the UI.
   */
  function testNodeTypeEditing() {
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types'));
    $this->drupalLogin($web_user);

    $instance = field_info_instance('node', 'body', 'page');
    $this->assertEqual($instance['label'], 'Body', t('Body field was found.'));

    // Verify that title and body fields are displayed.
    $this->drupalGet('node/add/page');
    $this->assertRaw('Title', t('Title field was found.'));
    $this->assertRaw('Body', t('Body field was found.'));

    // Rename the title field.
    $edit = array(
      'title_label' => 'Foo',
    );
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
    // Refresh the field information for the rest of the test.
    field_info_cache_clear();

    $this->drupalGet('node/add/page');
    $this->assertRaw('Foo', t('New title label was displayed.'));
    $this->assertNoRaw('Title', t('Old title label was not displayed.'));

    // Change the name, machine name and description.
    $edit = array(
      'name' => 'Bar',
      'type' => 'bar',
      'description' => 'Lorem ipsum.',
    );
    $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
    field_info_cache_clear();

    $this->drupalGet('node/add');
    $this->assertRaw('Bar', t('New name was displayed.'));
    $this->assertRaw('Lorem ipsum', t('New description was displayed.'));
    $this->clickLink('Bar');
    $this->assertEqual(url('node/add/bar', array('absolute' => TRUE)), $this->getUrl(), t('New machine name was used in URL.'));
    $this->assertRaw('Foo', t('Title field was found.'));
    $this->assertRaw('Body', t('Body field was found.'));

    // Remove the body field.
    $this->drupalPost('admin/structure/types/manage/bar/fields/body/delete', NULL, t('Delete'));
    // Resave the settings for this type.
    $this->drupalPost('admin/structure/types/manage/bar', array(), t('Save content type'));
    // Check that the body field doesn't exist.
    $this->drupalGet('node/add/bar');
    $this->assertNoRaw('Body', t('Body field was not found.'));
  }

  /**
   * Test that node_types_rebuild() correctly handles the 'disabled' flag.
   */
  function testNodeTypeStatus() {
    // Enable all core node modules, and all types should be active.
    module_enable(array('blog', 'book', 'poll'), FALSE);
    node_types_rebuild();
    $types = node_type_get_types();
    foreach (array('blog', 'book', 'poll', 'article', 'page') as $type) {
      $this->assertTrue(isset($types[$type]), t('%type is found in node types.', array('%type' => $type)));
      $this->assertTrue(isset($types[$type]->disabled) && empty($types[$type]->disabled), t('%type type is enabled.', array('%type' => $type)));
    }

    // Disable poll module and the respective type should be marked as disabled.
    module_disable(array('poll'), FALSE);
    node_types_rebuild();
    $types = node_type_get_types();
    $this->assertTrue(!empty($types['poll']->disabled), t("Poll module's node type disabled."));
    $this->assertTrue(isset($types['blog']) && empty($types['blog']->disabled), t("Blog module's node type still active."));

    // Disable blog module and the respective type should be marked as disabled.
    module_disable(array('blog'), FALSE);
    node_types_rebuild();
    $types = node_type_get_types();
    $this->assertTrue(!empty($types['blog']->disabled), t("Blog module's node type disabled."));
    $this->assertTrue(!empty($types['poll']->disabled), t("Poll module's node type still disabled."));

    // Disable book module and the respective type should still be active, since
    // it is not provided by hook_node_info().
    module_disable(array('book'), FALSE);
    node_types_rebuild();
    $types = node_type_get_types();
    $this->assertTrue(isset($types['book']) && empty($types['book']->disabled), t("Book module's node type still active."));
    $this->assertTrue(!empty($types['blog']->disabled), t("Blog module's node type still disabled."));
    $this->assertTrue(!empty($types['poll']->disabled), t("Poll module's node type still disabled."));
    $this->assertTrue(isset($types['article']) && empty($types['article']->disabled), t("Article node type still active."));
    $this->assertTrue(isset($types['page']) && empty($types['page']->disabled), t("Basic page node type still active."));

    // Re-enable the modules and verify that the types are active again.
    module_enable(array('blog', 'book', 'poll'), FALSE);
    node_types_rebuild();
    $types = node_type_get_types();
    foreach (array('blog', 'book', 'poll', 'article', 'page') as $type) {
      $this->assertTrue(isset($types[$type]), t('%type is found in node types.', array('%type' => $type)));
      $this->assertTrue(isset($types[$type]->disabled) && empty($types[$type]->disabled), t('%type type is enabled.', array('%type' => $type)));
    }
  }
}

/**
 * Test node type customizations persistence.
 */
class NodeTypePersistenceTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node type persist',
      'description' => 'Ensures that node type customization survives module enabling and disabling.',
      'group' => 'Node',
    );
  }

  /**
   * Test node type customizations persist through disable and uninstall.
   */
  function testNodeTypeCustomizationPersistence() {
    $web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types', 'administer modules'));
    $this->drupalLogin($web_user);
    $poll_key = 'modules[Core][poll][enable]';
    $poll_enable = array($poll_key => "1");
    $poll_disable = array($poll_key => FALSE);

    // Enable poll and verify that the node type is in the DB and is not
    // disabled.
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
    $this->assertNotIdentical($disabled, FALSE, t('Poll node type found in the database'));
    $this->assertEqual($disabled, 0, t('Poll node type is not disabled'));

    // Check that poll node type (uncustomized) shows up.
    $this->drupalGet('node/add');
    $this->assertText('poll', t('poll type is found on node/add'));

    // Customize poll description.
    $description = $this->randomName();
    $edit = array('description' => $description);
    $this->drupalPost('admin/structure/types/manage/poll', $edit, t('Save content type'));

    // Check that poll node type customization shows up.
    $this->drupalGet('node/add');
    $this->assertText($description, t('Customized description found'));

    // Disable poll and check that the node type gets disabled.
    $this->drupalPost('admin/modules', $poll_disable, t('Save configuration'));
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
    $this->assertEqual($disabled, 1, t('Poll node type is disabled'));
    $this->drupalGet('node/add');
    $this->assertNoText('poll', t('poll type is not found on node/add'));

    // Reenable poll and check that the customization survived the module
    // disable.
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
    $this->assertNotIdentical($disabled, FALSE, t('Poll node type found in the database'));
    $this->assertEqual($disabled, 0, t('Poll node type is not disabled'));
    $this->drupalGet('node/add');
    $this->assertText($description, t('Customized description found'));

    // Disable and uninstall poll.
    $this->drupalPost('admin/modules', $poll_disable, t('Save configuration'));
    $edit = array('uninstall[poll]' => 'poll');
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
    $this->drupalPost(NULL, array(), t('Uninstall'));
    $disabled = db_query('SELECT disabled FROM {node_type} WHERE type = :type', array(':type' => 'poll'))->fetchField();
    $this->assertTrue($disabled, t('Poll node type is in the database and is disabled'));
    $this->drupalGet('node/add');
    $this->assertNoText('poll', t('poll type is no longer found on node/add'));

    // Reenable poll and check that the customization survived the module
    // uninstall.
    $this->drupalPost('admin/modules', $poll_enable, t('Save configuration'));
    $this->drupalGet('node/add');
    $this->assertText($description, t('Customized description is found even after uninstall and reenable.'));
  }
}

/**
 * Rebuild the node_access table.
 */
class NodeAccessRebuildTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node access rebuild',
      'description' => 'Ensures that node access rebuild functions work correctly.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    $web_user = $this->drupalCreateUser(array('administer site configuration', 'access administration pages', 'access site reports'));
    $this->drupalLogin($web_user);
    $this->web_user = $web_user;
  }

  function testNodeAccessRebuild() {
    $this->drupalGet('admin/reports/status');
    $this->clickLink(t('Rebuild permissions'));
    $this->drupalPost(NULL, array(), t('Rebuild permissions'));
    $this->assertText(t('Content permissions have been rebuilt.'));
  }
}

/**
 * Test node administration page functionality.
 */
class NodeAdminTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node administration',
      'description' => 'Test node administration page functionality.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    // Remove the "view own unpublished content" permission which is set
    // by default for authenticated users so we can test this permission
    // correctly.
    user_role_revoke_permissions(DRUPAL_AUTHENTICATED_RID, array('view own unpublished content'));

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'access content overview', 'administer nodes', 'bypass node access'));
    $this->base_user_1 = $this->drupalCreateUser(array('access content overview'));
    $this->base_user_2 = $this->drupalCreateUser(array('access content overview', 'view own unpublished content'));
    $this->base_user_3 = $this->drupalCreateUser(array('access content overview', 'bypass node access'));
  }

  /**
   * Tests that the table sorting works on the content admin pages.
   */
  function testContentAdminSort() {
    $this->drupalLogin($this->admin_user);
    foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
      $this->drupalCreateNode(array('title' => $prefix . $this->randomName(6)));
    }

    // Test that the default sort by node.changed DESC actually fires properly.
    $nodes_query = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->orderBy('changed', 'DESC')
      ->execute()
      ->fetchCol();

    $nodes_form = array();
    $this->drupalGet('admin/content');
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
      $nodes_form[] = $input;
    }
    $this->assertEqual($nodes_query, $nodes_form, 'Nodes are sorted in the form according to the default query.');

    // Compare the rendered HTML node list to a query for the nodes ordered by
    // title to account for possible database-dependent sort order.
    $nodes_query = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->orderBy('title')
      ->execute()
      ->fetchCol();

    $nodes_form = array();
    $this->drupalGet('admin/content', array('query' => array('sort' => 'asc', 'order' => 'Title')));
    foreach ($this->xpath('//table/tbody/tr/td/div/input/@value') as $input) {
      $nodes_form[] = $input;
    }
    $this->assertEqual($nodes_query, $nodes_form, 'Nodes are sorted in the form the same as they are in the query.');
  }

  /**
   * Tests content overview with different user permissions.
   *
   * Taxonomy filters are tested separately.
   * @see TaxonomyNodeFilterTestCase
   */
  function testContentAdminPages() {
    $this->drupalLogin($this->admin_user);

    $nodes['published_page'] = $this->drupalCreateNode(array('type' => 'page'));
    $nodes['published_article'] = $this->drupalCreateNode(array('type' => 'article'));
    $nodes['unpublished_page_1'] = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->base_user_1->uid, 'status' => 0));
    $nodes['unpublished_page_2'] = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->base_user_2->uid, 'status' => 0));

    // Verify view, edit, and delete links for any content.
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
    foreach ($nodes as $node) {
      $this->assertLinkByHref('node/' . $node->nid);
      $this->assertLinkByHref('node/' . $node->nid . '/edit');
      $this->assertLinkByHref('node/' . $node->nid . '/delete');
      // Verify tableselect.
      $this->assertFieldByName('nodes[' . $node->nid . ']', '', t('Tableselect found.'));
    }

    // Verify filtering by publishing status.
    $edit = array(
      'status' => 'status-1',
    );
    $this->drupalPost(NULL, $edit, t('Filter'));

    $this->assertRaw(t('where %property is %value', array('%property' => t('status'), '%value' => 'published')), t('Content list is filtered by status.'));

    $this->assertLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
    $this->assertLinkByHref('node/' . $nodes['published_article']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');

    // Verify filtering by status and content type.
    $edit = array(
      'type' => 'page',
    );
    $this->drupalPost(NULL, $edit, t('Refine'));

    $this->assertRaw(t('where %property is %value', array('%property' => t('status'), '%value' => 'published')), t('Content list is filtered by status.'));
    $this->assertRaw(t('and where %property is %value', array('%property' => t('type'), '%value' => 'Basic page')), t('Content list is filtered by content type.'));

    $this->assertLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/edit');

    // Verify no operation links are displayed for regular users.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_1);
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
    $this->assertLinkByHref('node/' . $nodes['published_page']->nid);
    $this->assertLinkByHref('node/' . $nodes['published_article']->nid);
    $this->assertNoLinkByHref('node/' . $nodes['published_page']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['published_page']->nid . '/delete');
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['published_article']->nid . '/delete');

    // Verify no unpublished content is displayed without permission.
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid);
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/delete');

    // Verify no tableselect.
    $this->assertNoFieldByName('nodes[' . $nodes['published_page']->nid . ']', '', t('No tableselect found.'));

    // Verify unpublished content is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_2);
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
    $this->assertLinkByHref('node/' . $nodes['unpublished_page_2']->nid);
    // Verify no operation links are displayed.
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_2']->nid . '/delete');

    // Verify user cannot see unpublished content of other users.
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid);
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/edit');
    $this->assertNoLinkByHref('node/' . $nodes['unpublished_page_1']->nid . '/delete');

    // Verify no tableselect.
    $this->assertNoFieldByName('nodes[' . $nodes['unpublished_page_2']->nid . ']', '', t('No tableselect found.'));

    // Verify node access can be bypassed.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_3);
    $this->drupalGet('admin/content');
    $this->assertResponse(200);
    foreach ($nodes as $node) {
      $this->assertLinkByHref('node/' . $node->nid);
      $this->assertLinkByHref('node/' . $node->nid . '/edit');
      $this->assertLinkByHref('node/' . $node->nid . '/delete');
    }
  }
}

/**
 * Test node title.
 */
class NodeTitleTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Node title',
      'description' => 'Test node title.',
      'group' => 'Node'
    );
  }

  function setUp() {
    parent::setUp();
    $this->admin_user = $this->drupalCreateUser(array('administer nodes', 'create article content', 'create page content'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   *  Create one node and test if the node title has the correct value.
   */
  function testNodeTitle() {
    // Create "Basic page" content with title.
    // Add the node to the frontpage so we can test if teaser links are clickable.
    $settings = array(
      'title' => $this->randomName(8),
      'promote' => 1,
    );
    $node = $this->drupalCreateNode($settings);

    // Test <title> tag.
    $this->drupalGet("node/$node->nid");
    $xpath = '//title';
    $this->assertEqual(current($this->xpath($xpath)), $node->title .' | Drupal', 'Page title is equal to node title.', 'Node');

    // Test breadcrumb in comment preview.
    $this->drupalGet("comment/reply/$node->nid");
    $xpath = '//div[@class="breadcrumb"]/a[last()]';
    $this->assertEqual(current($this->xpath($xpath)), $node->title, 'Node breadcrumb is equal to node title.', 'Node');

    // Test node title in comment preview.
    $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');

    // Test node title is clickable on teaser list (/node).
    $this->drupalGet('node');
    $this->clickLink($node->title);
  }
}

/**
 * Test the node_feed() functionality.
 */
class NodeFeedTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node feed',
      'description' => 'Ensures that node_feed() functions correctly.',
      'group' => 'Node',
   );
  }

  /**
   * Ensure that node_feed accepts and prints extra channel elements.
   */
  function testNodeFeedExtraChannelElements() {
    ob_start();
    node_feed(array(), array('copyright' => 'Drupal is a registered trademark of Dries Buytaert.'));
    $output = ob_get_clean();

    $this->assertTrue(strpos($output, '<copyright>Drupal is a registered trademark of Dries Buytaert.</copyright>') !== FALSE);
  }
}

/**
 * Functional tests for the node module blocks.
 */
class NodeBlockFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node blocks',
      'description' => 'Test node block functionality.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp('node', 'block');

    // Create users and test node.
    $this->admin_user = $this->drupalCreateUser(array('administer content types', 'administer nodes', 'administer blocks'));
    $this->web_user = $this->drupalCreateUser(array('access content', 'create article content'));
  }

  /**
   * Test the recent comments block.
   */
  function testRecentNodeBlock() {
    $this->drupalLogin($this->admin_user);

    // Disallow anonymous users to view content.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access content' => FALSE,
    ));

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

    // Set block title and variables.
    $block = array(
      'title' => $this->randomName(),
      'node_recent_block_count' => 2,
    );
    $this->drupalPost('admin/structure/block/manage/node/recent/configure', $block, t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block saved.'));

    // Test that block is not visible without nodes
    $this->drupalGet('');
    $this->assertText(t('No content available.'), t('Block with "No content available." found.'));

    // Add some test nodes.
    $default_settings = array('uid' => $this->web_user->uid, 'type' => 'article');
    $node1 = $this->drupalCreateNode($default_settings);
    $node2 = $this->drupalCreateNode($default_settings);
    $node3 = $this->drupalCreateNode($default_settings);

    // Change the changed time for node so that we can test ordering.
    db_update('node')
      ->fields(array(
        'changed' => $node1->changed + 100,
      ))
      ->condition('nid', $node2->nid)
      ->execute();
    db_update('node')
      ->fields(array(
        'changed' => $node1->changed + 200,
      ))
      ->condition('nid', $node3->nid)
      ->execute();

    // Test that a user without the 'access content' permission cannot
    // see the block.
    $this->drupalLogout();
    $this->drupalGet('');
    $this->assertNoText($block['title'], t('Block was not found.'));

    // Test that only the 2 latest nodes are shown.
    $this->drupalLogin($this->web_user);
    $this->assertNoText($node1->title, t('Node not found in block.'));
    $this->assertText($node2->title, t('Node found in block.'));
    $this->assertText($node3->title, t('Node found in block.'));

    // Check to make sure nodes are in the right order.
    $this->assertTrue($this->xpath('//div[@id="block-node-recent"]/div/table/tbody/tr[position() = 1]/td/div/a[text() = "' . $node3->title . '"]'), t('Nodes were ordered correctly in block.'));

    // Set the number of recent nodes to show to 10.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    $block = array(
      'node_recent_block_count' => 10,
    );
    $this->drupalPost('admin/structure/block/manage/node/recent/configure', $block, t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block saved.'));

    // Post an additional node.
    $node4 = $this->drupalCreateNode($default_settings);

    // Test that all four nodes are shown.
    $this->drupalGet('');
    $this->assertText($node1->title, t('Node found in block.'));
    $this->assertText($node2->title, t('Node found in block.'));
    $this->assertText($node3->title, t('Node found in block.'));
    $this->assertText($node4->title, t('Node found in block.'));

    // Create the custom block.
    $custom_block = array();
    $custom_block['info'] = $this->randomName();
    $custom_block['title'] = $this->randomName();
    $custom_block['types[article]'] = TRUE;
    $custom_block['body[value]'] = $this->randomName(32);
    $custom_block['regions[' . variable_get('theme_default', 'bartik') . ']'] = 'content';
    if ($admin_theme = variable_get('admin_theme')) {
      $custom_block['regions[' . $admin_theme . ']'] = 'content';
    }
    $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));

    $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
    $this->assertTrue($bid, t('Custom block with visibility rule was created.'));

    // Verify visibility rules.
    $this->drupalGet('');
    $this->assertNoText($custom_block['title'], t('Block was displayed on the front page.'));
    $this->drupalGet('node/add/article');
    $this->assertText($custom_block['title'], t('Block was displayed on the node/add/article page.'));
    $this->drupalGet('node/' . $node1->nid);
    $this->assertText($custom_block['title'], t('Block was displayed on the node/N.'));

    // Delete the created custom block & verify that it's been deleted.
    $this->drupalPost('admin/structure/block/manage/block/' . $bid . '/delete', array(), t('Delete'));
    $bid = db_query("SELECT 1 FROM {block_node_type} WHERE module = 'block' AND delta = :delta", array(':delta' => $bid))->fetchField();
    $this->assertFalse($bid, t('Custom block was deleted.'));
  }
}
/**
 * Test multistep node forms basic options.
 */
class MultiStepNodeFormBasicOptionsTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Multistep node form basic options',
      'description' => 'Test the persistence of basic options through multiple steps.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp('poll');
    $web_user = $this->drupalCreateUser(array('administer nodes', 'create poll content'));
    $this->drupalLogin($web_user);
  }

  /**
   * Change the default values of basic options to ensure they persist.
   */
  function testMultiStepNodeFormBasicOptions() {
    $edit = array(
      'title' => 'a',
      'status' => FALSE,
      'promote' => FALSE,
      'sticky' => 1,
      'choice[new:0][chtext]' => 'a',
      'choice[new:1][chtext]' => 'a',
    );
    $this->drupalPost('node/add/poll', $edit, t('More choices'));
    $this->assertNoFieldChecked('edit-status', 'status stayed unchecked');
    $this->assertNoFieldChecked('edit-promote', 'promote stayed unchecked');
    $this->assertFieldChecked('edit-sticky', 'sticky stayed checked');
  }
}

/**
 * Test to ensure that a node's content is always rebuilt.
 */
class NodeBuildContent extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Rebuild content',
      'description' => 'Test the rebuilding of content for different build modes.',
      'group' => 'Node',
    );
  }

 /**
  * Test to ensure that a node's content array is rebuilt on every call to node_build_content().
  */
  function testNodeRebuildContent() {
    $node = $this->drupalCreateNode();

    // Set a property in the content array so we can test for its existence later on.
    $node->content['test_content_property'] = array('#value' => $this->randomString());
    $content = node_build_content($node);

    // If the property doesn't exist it means the node->content was rebuilt.
    $this->assertFalse(isset($content['test_content_property']), t('Node content was emptied prior to being built.'));
  }
}

/**
 * Tests node_query_node_access_alter().
 */
class NodeQueryAlter extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node query alter',
      'description' => 'Test that node access queries are properly altered by the node module.',
      'group' => 'Node',
    );
  }

  /**
   * User with permission to view content.
   */
  protected $accessUser;

  /**
   * User without permission to view content.
   */
  protected $noAccessUser;

  function setUp() {
    parent::setUp('node_access_test');
    node_access_rebuild();

    // Create some content.
    $this->drupalCreateNode();
    $this->drupalCreateNode();
    $this->drupalCreateNode();
    $this->drupalCreateNode();

    // Create user with simple node access permission. The 'node test view'
    // permission is implemented and granted by the node_access_test module.
    $this->accessUser = $this->drupalCreateUser(array('access content overview', 'access content', 'node test view'));
    $this->noAccessUser = $this->drupalCreateUser(array('access content overview', 'access content'));
    $this->noAccessUser2 = $this->drupalCreateUser(array('access content overview', 'access content'));
  }

  /**
   * Tests that node access permissions are followed.
   */
  function testNodeQueryAlterWithUI() {
    // Verify that a user with access permission can see at least one node.
    $this->drupalLogin($this->accessUser);
    $this->drupalGet('node_access_test_page');
    $this->assertText('Yes, 4 nodes', "4 nodes were found for access user");
    $this->assertNoText('Exception', "No database exception");

    // Test the content overview page.
    $this->drupalGet('admin/content');
    $table_rows = $this->xpath('//tbody/tr');
    $this->assertEqual(4, count($table_rows), "4 nodes were found for access user");

    // Verify that a user with no access permission cannot see nodes.
    $this->drupalLogin($this->noAccessUser);
    $this->drupalGet('node_access_test_page');
    $this->assertText('No nodes', "No nodes were found for no access user");
    $this->assertNoText('Exception', "No database exception");

    $this->drupalGet('admin/content');
    $this->assertText(t('No content available.'));
  }

  /**
   * Lower-level test of 'node_access' query alter, for user with access.
   *
   * Verifies that a non-standard table alias can be used, and that a
   * user with node access can view the nodes.
   */
  function testNodeQueryAlterLowLevelWithAccess() {
    // User with access should be able to view 4 nodes.
    try {
      $query = db_select('node', 'mytab')
        ->fields('mytab');
      $query->addTag('node_access');
      $query->addMetaData('op', 'view');
      $query->addMetaData('account', $this->accessUser);

      $result = $query->execute()->fetchAll();
      $this->assertEqual(count($result), 4, t('User with access can see correct nodes'));
    }
    catch (Exception $e) {
      $this->fail(t('Altered query is malformed'));
    }
  }

  /**
   * Lower-level test of 'node_access' query alter, for user without access.
   *
   * Verifies that a non-standard table alias can be used, and that a
   * user without node access cannot view the nodes.
   */
  function testNodeQueryAlterLowLevelNoAccess() {
    // User without access should be able to view 0 nodes.
    try {
      $query = db_select('node', 'mytab')
        ->fields('mytab');
      $query->addTag('node_access');
      $query->addMetaData('op', 'view');
      $query->addMetaData('account', $this->noAccessUser);

      $result = $query->execute()->fetchAll();
      $this->assertEqual(count($result), 0, t('User with no access cannot see nodes'));
    }
    catch (Exception $e) {
      $this->fail(t('Altered query is malformed'));
    }
  }

  /**
   * Lower-level test of 'node_access' query alter, for edit access.
   *
   * Verifies that a non-standard table alias can be used, and that a
   * user with view-only node access cannot edit the nodes.
   */
  function testNodeQueryAlterLowLevelEditAccess() {
    // User with view-only access should not be able to edit nodes.
    try {
      $query = db_select('node', 'mytab')
        ->fields('mytab');
      $query->addTag('node_access');
      $query->addMetaData('op', 'update');
      $query->addMetaData('account', $this->accessUser);

      $result = $query->execute()->fetchAll();
      $this->assertEqual(count($result), 0, t('User with view-only access cannot edit nodes'));
    }
    catch (Exception $e) {
      $this->fail($e->getMessage());
      $this->fail((string) $query);
      $this->fail(t('Altered query is malformed'));
    }
  }

  /**
   * Lower-level test of 'node_access' query alter override.
   *
   * Verifies that node_access_view_all_nodes() is called from
   * node_query_node_access_alter().  We do this by checking that
   * a user which normally would not have view privileges is able
   * to view the nodes when we add a record to {node_access} paired
   * with a corresponding privilege in hook_node_grants().
   */
  function testNodeQueryAlterOverride() {
    $record = array(
      'nid' => 0,
      'gid' => 0,
      'realm' => 'node_access_all',
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
    );
    drupal_write_record('node_access', $record);

    // Test that the noAccessUser still doesn't have the 'view'
    // privilege after adding the node_access record.
    drupal_static_reset('node_access_view_all_nodes');
    try {
      $query = db_select('node', 'mytab')
        ->fields('mytab');
      $query->addTag('node_access');
      $query->addMetaData('op', 'view');
      $query->addMetaData('account', $this->noAccessUser);

      $result = $query->execute()->fetchAll();
      $this->assertEqual(count($result), 0, t('User view privileges are not overridden'));
    }
    catch (Exception $e) {
      $this->fail(t('Altered query is malformed'));
    }

    // Have node_test_node_grants return a node_access_all privilege,
    // to grant the noAccessUser 'view' access.  To verify that
    // node_access_view_all_nodes is properly checking the specified
    // $account instead of the global $user, we will log in as
    // noAccessUser2.
    $this->drupalLogin($this->noAccessUser2);
    variable_set('node_test_node_access_all_uid', $this->noAccessUser->uid);
    drupal_static_reset('node_access_view_all_nodes');
    try {
      $query = db_select('node', 'mytab')
        ->fields('mytab');
      $query->addTag('node_access');
      $query->addMetaData('op', 'view');
      $query->addMetaData('account', $this->noAccessUser);

      $result = $query->execute()->fetchAll();
      $this->assertEqual(count($result), 4, t('User view privileges are overridden'));
    }
    catch (Exception $e) {
      $this->fail(t('Altered query is malformed'));
    }
    variable_del('node_test_node_access_all_uid');
  }
}


/**
 * Tests node_query_entity_field_access_alter().
 */
class NodeEntityFieldQueryAlter extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node entity query alter',
      'description' => 'Test that node access entity queries are properly altered by the node module.',
      'group' => 'Node',
    );
  }

  /**
   * User with permission to view content.
   */
  protected $accessUser;

  /**
   * User without permission to view content.
   */
  protected $noAccessUser;

  function setUp() {
    parent::setUp('node_access_test');
    node_access_rebuild();

    // Creating 4 nodes with an entity field so we can test that sort of query
    // alter. All field values starts with 'A' so we can identify and fetch them
    // in the node_access_test module.
    $settings = array('language' => LANGUAGE_NONE);
    for ($i = 0; $i < 4; $i++) {
      $body = array(
        'value' => 'A' . $this->randomName(32),
        'format' => filter_default_format(),
      );
      $settings['body'][LANGUAGE_NONE][0] = $body;
      $this->drupalCreateNode($settings);
    }

    // Create user with simple node access permission. The 'node test view'
    // permission is implemented and granted by the node_access_test module.
    $this->accessUser = $this->drupalCreateUser(array('access content', 'node test view'));
    $this->noAccessUser = $this->drupalCreateUser(array('access content'));
  }

  /**
   * Tests that node access permissions are followed.
   */
  function testNodeQueryAlterWithUI() {
    // Verify that a user with access permission can see at least one node.
    $this->drupalLogin($this->accessUser);
    $this->drupalGet('node_access_entity_test_page');
    $this->assertText('Yes, 4 nodes', "4 nodes were found for access user");
    $this->assertNoText('Exception', "No database exception");

    // Verify that a user with no access permission cannot see nodes.
    $this->drupalLogin($this->noAccessUser);
    $this->drupalGet('node_access_entity_test_page');
    $this->assertText('No nodes', "No nodes were found for no access user");
    $this->assertNoText('Exception', "No database exception");
  }
}

/**
 * Test node token replacement in strings.
 */
class NodeTokenReplaceTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Node token replacement',
      'description' => 'Generates text using placeholders for dummy content to check node token replacement.',
      'group' => 'Node',
    );
  }

  /**
   * Creates a node, then tests the tokens generated from it.
   */
  function testNodeTokenReplacement() {
    global $language;
    $url_options = array(
      'absolute' => TRUE,
      'language' => $language,
    );

    // Create a user and a node.
    $account = $this->drupalCreateUser();
    $settings = array(
      'type' => 'article',
      'uid' => $account->uid,
      'title' => '<blink>Blinking Text</blink>',
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(32), 'summary' => $this->randomName(16)))),
    );
    $node = $this->drupalCreateNode($settings);

    // Load node so that the body and summary fields are structured properly.
    $node = node_load($node->nid);
    $instance = field_info_instance('node', 'body', $node->type);

    // Generate and test sanitized tokens.
    $tests = array();
    $langcode = entity_language('node', $node);
    $tests['[node:nid]'] = $node->nid;
    $tests['[node:vid]'] = $node->vid;
    $tests['[node:tnid]'] = $node->tnid;
    $tests['[node:type]'] = 'article';
    $tests['[node:type-name]'] = 'Article';
    $tests['[node:title]'] = check_plain($node->title);
    $tests['[node:body]'] = _text_sanitize($instance, $langcode, $node->body[$langcode][0], 'value');
    $tests['[node:summary]'] = _text_sanitize($instance, $langcode, $node->body[$langcode][0], 'summary');
    $tests['[node:language]'] = check_plain($langcode);
    $tests['[node:url]'] = url('node/' . $node->nid, $url_options);
    $tests['[node:edit-url]'] = url('node/' . $node->nid . '/edit', $url_options);
    $tests['[node:author]'] = check_plain(format_username($account));
    $tests['[node:author:uid]'] = $node->uid;
    $tests['[node:author:name]'] = check_plain(format_username($account));
    $tests['[node:created:since]'] = format_interval(REQUEST_TIME - $node->created, 2, $language->language);
    $tests['[node:changed:since]'] = format_interval(REQUEST_TIME - $node->changed, 2, $language->language);

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

    foreach ($tests as $input => $expected) {
      $output = token_replace($input, array('node' => $node), array('language' => $language));
      $this->assertEqual($output, $expected, t('Sanitized node token %token replaced.', array('%token' => $input)));
    }

    // Generate and test unsanitized tokens.
    $tests['[node:title]'] = $node->title;
    $tests['[node:body]'] = $node->body[$langcode][0]['value'];
    $tests['[node:summary]'] = $node->body[$langcode][0]['summary'];
    $tests['[node:language]'] = $langcode;
    $tests['[node:author:name]'] = format_username($account);

    foreach ($tests as $input => $expected) {
      $output = token_replace($input, array('node' => $node), array('language' => $language, 'sanitize' => FALSE));
      $this->assertEqual($output, $expected, t('Unsanitized node token %token replaced.', array('%token' => $input)));
    }
  }
}

/**
 * Tests user permissions for node revisions.
 */
class NodeRevisionPermissionsTestCase extends DrupalWebTestCase {
  protected $node_revisions = array();
  protected $accounts = array();

  // Map revision permission names to node revision access ops.
  protected $map = array(
    'view' => 'view revisions',
    'update' => 'revert revisions',
    'delete' => 'delete revisions',
  );

  public static function getInfo() {
    return array(
      'name' => 'Node revision permissions',
      'description' => 'Tests user permissions for node revision operations.',
      'group' => 'Node',
    );
  }

  function setUp() {
    parent::setUp();

    // Create a node with several revisions.
    $node = $this->drupalCreateNode();
    $this->node_revisions[] = $node;

    for ($i = 0; $i < 3; $i++) {
      // Create a revision for the same nid and settings with a random log.
      $revision = clone $node;
      $revision->revision = 1;
      $revision->log = $this->randomName(32);
      node_save($revision);
      $this->node_revisions[] = $revision;
    }

    // Create three users, one with each revision permission.
    foreach ($this->map as $op => $permission) {
      // Create the user.
      $account = $this->drupalCreateUser(
        array(
          'access content',
          'edit any page content',
          'delete any page content',
          $permission,
        )
      );
      $account->op = $op;
      $this->accounts[] = $account;
    }

    // Create an admin account (returns TRUE for all revision permissions).
    $admin_account = $this->drupalCreateUser(array('access content', 'administer nodes'));
    $admin_account->is_admin = TRUE;
    $this->accounts['admin'] = $admin_account;

    // Create a normal account (returns FALSE for all revision permissions).
    $normal_account = $this->drupalCreateUser();
    $normal_account->op = FALSE;
    $this->accounts[] = $normal_account;
  }

  /**
   * Tests the _node_revision_access() function.
   */
  function testNodeRevisionAccess() {
    $revision = $this->node_revisions[1];

    $parameters = array(
      'op' => array_keys($this->map),
      'account' => $this->accounts,
    );

    $permutations = $this->generatePermutations($parameters);
    foreach ($permutations as $case) {
      if (!empty($case['account']->is_admin) || $case['op'] == $case['account']->op) {
        $this->assertTrue(_node_revision_access($revision, $case['op'], $case['account']), "{$this->map[$case['op']]} granted.");
      }
      else {
        $this->assertFalse(_node_revision_access($revision, $case['op'], $case['account']), "{$this->map[$case['op']]} not granted.");
      }
    }

    // Test that access is FALSE for a node administrator with an invalid $node
    // or $op parameters.
    $admin_account = $this->accounts['admin'];
    $this->assertFalse(_node_revision_access(FALSE, 'view', $admin_account), '_node_revision_access() returns FALSE with an invalid node.');
    $this->assertFalse(_node_revision_access($revision, 'invalid-op', $admin_account), '_node_revision_access() returns FALSE with an invalid op.');

    // Test that the $account parameter defaults to the "logged in" user.
    $original_user = $GLOBALS['user'];
    $GLOBALS['user'] = $admin_account;
    $this->assertTrue(_node_revision_access($revision, 'view'), '_node_revision_access() returns TRUE when used with global user.');
    $GLOBALS['user'] = $original_user;
  }
}

/**
 * Tests pagination with a node access module enabled.
 */
class NodeAccessPagerTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node access pagination',
      'description' => 'Test access controlled node views have the right amount of comment pages.',
      'group' => 'Node',
    );
  }

  public function setUp() {
    parent::setUp('node_access_test', 'comment', 'forum');
    node_access_rebuild();
    $this->web_user = $this->drupalCreateUser(array('access content', 'access comments', 'node test view'));
  }

  /**
   * Tests the comment pager for nodes with multiple grants per realm.
   */
  public function testCommentPager() {
    // Create a node.
    $node = $this->drupalCreateNode();

    // Create 60 comments.
    for ($i = 0; $i < 60; $i++) {
      $comment = new stdClass();
      $comment->cid = 0;
      $comment->pid = 0;
      $comment->uid = $this->web_user->uid;
      $comment->nid = $node->nid;
      $comment->subject = $this->randomName();
      $comment->comment_body = array(
        LANGUAGE_NONE => array(
          array('value' => $this->randomName()),
        ),
      );
      comment_save($comment);
    }

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

    // View the node page. With the default 50 comments per page there should
    // be two pages (0, 1) but no third (2) page.
    $this->drupalGet('node/' . $node->nid);
    $this->assertText($node->title);
    $this->assertText(t('Comments'));
    $this->assertRaw('page=1');
    $this->assertNoRaw('page=2');
  }

  /**
   * Tests the forum node pager for nodes with multiple grants per realm.
   */
  public function testForumPager() {
    // Look up the forums vocabulary ID.
    $vid = variable_get('forum_nav_vocabulary', 0);
    $this->assertTrue($vid, 'Forum navigation vocabulary ID is set.');

    // Look up the general discussion term.
    $tree = taxonomy_get_tree($vid, 0, 1);
    $tid = reset($tree)->tid;
    $this->assertTrue($tid, 'General discussion term is found in the forum vocabulary.');

    // Create 30 nodes.
    for ($i = 0; $i < 30; $i++) {
      $this->drupalCreateNode(array(
        'nid' => NULL,
        'type' => 'forum',
        'taxonomy_forums' => array(
          LANGUAGE_NONE => array(
            array('tid' => $tid, 'vid' => $vid, 'vocabulary_machine_name' => 'forums'),
          ),
        ),
      ));
    }

    // View the general discussion forum page. With the default 25 nodes per
    // page there should be two pages for 30 nodes, no more.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('forum/' . $tid);
    $this->assertRaw('page=1');
    $this->assertNoRaw('page=2');
  }
}


/**
 * Tests the interaction of the node access system with fields.
 */
class NodeAccessFieldTestCase extends NodeWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node access and fields',
      'description' => 'Tests the interaction of the node access system with fields.',
      'group' => 'Node',
    );
  }

  public function setUp() {
    parent::setUp('node_access_test', 'field_ui');
    node_access_rebuild();

    // Create some users.
    $this->admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
    $this->content_admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));

    // Add a custom field to the page content type.
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
    $this->field = field_create_field(array('field_name' => $this->field_name, 'type' => 'text'));
    $this->instance = field_create_instance(array(
      'field_name' => $this->field_name,
      'entity_type' => 'node',
      'bundle' => 'page',
    ));
  }

  /**
   * Tests administering fields when node access is restricted.
   */
  function testNodeAccessAdministerField() {
    // Create a page node.
    $langcode = LANGUAGE_NONE;
    $field_data = array();
    $value = $field_data[$langcode][0]['value'] = $this->randomName();
    $node = $this->drupalCreateNode(array($this->field_name => $field_data));

    // Log in as the administrator and confirm that the field value is present.
    $this->drupalLogin($this->admin_user);
    $this->drupalGet("node/{$node->nid}");
    $this->assertText($value, 'The saved field value is visible to an administrator.');

    // Log in as the content admin and try to view the node.
    $this->drupalLogin($this->content_admin_user);
    $this->drupalGet("node/{$node->nid}");
    $this->assertText('Access denied', 'Access is denied for the content admin.');

    // Modify the field default as the content admin.
    $edit = array();
    $default = 'Sometimes words have two meanings';
    $edit["{$this->field_name}[$langcode][0][value]"] = $default;
    $this->drupalPost(
      "admin/structure/types/manage/page/fields/{$this->field_name}",
      $edit,
      t('Save settings')
    );

    // Log in as the administrator.
    $this->drupalLogin($this->admin_user);

    // Confirm that the existing node still has the correct field value.
    $this->drupalGet("node/{$node->nid}");
    $this->assertText($value, 'The original field value is visible to an administrator.');

    // Confirm that the new default value appears when creating a new node.
    $this->drupalGet('node/add/page');
    $this->assertRaw($default, 'The updated default value is displayed when creating a new node.');
  }
}

/**
 * Tests changing view modes for nodes.
 */
class NodeEntityViewModeAlterTest extends NodeWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Node entity view mode',
      'description' => 'Test changing view mode.',
      'group' => 'Node'
    );
  }

  function setUp() {
    parent::setUp(array('node_test'));
  }

  /**
   * Create a "Basic page" node and verify its consistency in the database.
   */
  function testNodeViewModeChange() {
    $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
    $this->drupalLogin($web_user);

    // Create a node.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName(8);
    $edit["body[$langcode][0][value]"] = t('Data that should appear only in the body for the node.');
    $edit["body[$langcode][0][summary]"] = t('Extra data that should appear only in the teaser for the node.');
    $this->drupalPost('node/add/page', $edit, t('Save'));

    $node = $this->drupalGetNodeByTitle($edit["title"]);

    // Set the flag to alter the view mode and view the node.
    variable_set('node_test_change_view_mode', 'teaser');
    $this->drupalGet('node/' . $node->nid);

    // Check that teaser mode is viewed.
    $this->assertText('Extra data that should appear only in the teaser for the node.', 'Teaser text present');
    // Make sure body text is not present.
    $this->assertNoText('Data that should appear only in the body for the node.', 'Body text not present');

    // Test that the correct build mode has been set.
    $build = node_view($node);
    $this->assertEqual($build['#view_mode'], 'teaser', 'The view mode has correctly been set to teaser.');
  }
}