system.test 109 KB
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 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
<?php

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

/**
 * Helper class for module test cases.
 */
class ModuleTestCase extends DrupalWebTestCase {
  protected $admin_user;

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

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer modules'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Assert there are tables that begin with the specified base table name.
   *
   * @param $base_table
   *   Beginning of table name to look for.
   * @param $count
   *   (optional) Whether or not to assert that there are tables that match the
   *   specified base table. Defaults to TRUE.
   */
  function assertTableCount($base_table, $count = TRUE) {
    $tables = db_find_tables(Database::getConnection()->prefixTables('{' . $base_table . '}') . '%');

    if ($count) {
      return $this->assertTrue($tables, format_string('Tables matching "@base_table" found.', array('@base_table' => $base_table)));
    }
    return $this->assertFalse($tables, format_string('Tables matching "@base_table" not found.', array('@base_table' => $base_table)));
  }

  /**
   * Assert that all tables defined in a module's hook_schema() exist.
   *
   * @param $module
   *   The name of the module.
   */
  function assertModuleTablesExist($module) {
    $tables = array_keys(drupal_get_schema_unprocessed($module));
    $tables_exist = TRUE;
    foreach ($tables as $table) {
      if (!db_table_exists($table)) {
        $tables_exist = FALSE;
      }
    }
    return $this->assertTrue($tables_exist, format_string('All database tables defined by the @module module exist.', array('@module' => $module)));
  }

  /**
   * Assert that none of the tables defined in a module's hook_schema() exist.
   *
   * @param $module
   *   The name of the module.
   */
  function assertModuleTablesDoNotExist($module) {
    $tables = array_keys(drupal_get_schema_unprocessed($module));
    $tables_exist = FALSE;
    foreach ($tables as $table) {
      if (db_table_exists($table)) {
        $tables_exist = TRUE;
      }
    }
    return $this->assertFalse($tables_exist, format_string('None of the database tables defined by the @module module exist.', array('@module' => $module)));
  }

  /**
   * Assert the list of modules are enabled or disabled.
   *
   * @param $modules
   *   Module list to check.
   * @param $enabled
   *   Expected module state.
   */
  function assertModules(array $modules, $enabled) {
    module_list(TRUE);
    foreach ($modules as $module) {
      if ($enabled) {
        $message = 'Module "@module" is enabled.';
      }
      else {
        $message = 'Module "@module" is not enabled.';
      }
      $this->assertEqual(module_exists($module), $enabled, format_string($message, array('@module' => $module)));
    }
  }

  /**
   * Verify a log entry was entered for a module's status change.
   * Called in the same way of the expected original watchdog() execution.
   *
   * @param $type
   *   The category to which this message belongs.
   * @param $message
   *   The message to store in the log. Keep $message translatable
   *   by not concatenating dynamic values into it! Variables in the
   *   message should be added by using placeholder strings alongside
   *   the variables argument to declare the value of the placeholders.
   *   See t() for documentation on how $message and $variables interact.
   * @param $variables
   *   Array of variables to replace in the message on display or
   *   NULL if message is already translated or not possible to
   *   translate.
   * @param $severity
   *   The severity of the message, as per RFC 3164.
   * @param $link
   *   A link to associate with the message.
   */
  function assertLogMessage($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = '') {
    $count = db_select('watchdog', 'w')
      ->condition('type', $type)
      ->condition('message', $message)
      ->condition('variables', serialize($variables))
      ->condition('severity', $severity)
      ->condition('link', $link)
      ->countQuery()
      ->execute()
      ->fetchField();
    $this->assertTrue($count > 0, format_string('watchdog table contains @count rows for @message', array('@count' => $count, '@message' => $message)));
  }
}

/**
 * Test module enabling/disabling functionality.
 */
class EnableDisableTestCase extends ModuleTestCase {
  protected $profile = 'testing';

  public static function getInfo() {
    return array(
      'name' => 'Enable/disable modules',
      'description' => 'Enable/disable core module and confirm table creation/deletion.',
      'group' => 'Module',
    );
  }

  /**
   * Test that all core modules can be enabled, disabled and uninstalled.
   */
  function testEnableDisable() {
    // Try to enable, disable and uninstall all core modules, unless they are
    // hidden or required.
    $modules = system_rebuild_module_data();
    foreach ($modules as $name => $module) {
      if ($module->info['package'] != 'Core' || !empty($module->info['hidden']) || !empty($module->info['required'])) {
        unset($modules[$name]);
      }
    }
    $this->assertTrue(count($modules), format_string('Found @count core modules that we can try to enable in this test.', array('@count' => count($modules))));

    // Enable the dblog module first, since we will be asserting the presence
    // of log messages throughout the test.
   if (isset($modules['dblog'])) {
     $modules = array('dblog' => $modules['dblog']) + $modules;
   }

   // Set a variable so that the hook implementations in system_test.module
   // will display messages via drupal_set_message().
   variable_set('test_verbose_module_hooks', TRUE);

    // Throughout this test, some modules may be automatically enabled (due to
    // dependencies). We'll keep track of them in an array, so we can handle
    // them separately.
    $automatically_enabled = array();

    // Go through each module in the list and try to enable it (unless it was
    // already enabled automatically due to a dependency).
    foreach ($modules as $name => $module) {
      if (empty($automatically_enabled[$name])) {
        // Start a list of modules that we expect to be enabled this time.
        $modules_to_enable = array($name);

        // Find out if the module has any dependencies that aren't enabled yet;
        // if so, add them to the list of modules we expect to be automatically
        // enabled.
        foreach (array_keys($module->requires) as $dependency) {
          if (isset($modules[$dependency]) && empty($automatically_enabled[$dependency])) {
            $modules_to_enable[] = $dependency;
            $automatically_enabled[$dependency] = TRUE;
          }
        }

        // Check that each module is not yet enabled and does not have any
        // database tables yet.
        foreach ($modules_to_enable as $module_to_enable) {
          $this->assertModules(array($module_to_enable), FALSE);
          $this->assertModuleTablesDoNotExist($module_to_enable);
        }

        // Install and enable the module.
        $edit = array();
        $edit['modules[Core][' . $name . '][enable]'] = $name;
        $this->drupalPost('admin/modules', $edit, t('Save configuration'));
        // Handle the case where modules were installed along with this one and
        // where we therefore hit a confirmation screen.
        if (count($modules_to_enable) > 1) {
          $this->drupalPost(NULL, array(), t('Continue'));
        }
        $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');

        // Check that hook_modules_installed() and hook_modules_enabled() were
        // invoked with the expected list of modules, that each module's
        // database tables now exist, and that appropriate messages appear in
        // the logs.
        foreach ($modules_to_enable as $module_to_enable) {
          $this->assertText(t('hook_modules_installed fired for @module', array('@module' => $module_to_enable)));
          $this->assertText(t('hook_modules_enabled fired for @module', array('@module' => $module_to_enable)));
          $this->assertModules(array($module_to_enable), TRUE);
          $this->assertModuleTablesExist($module_to_enable);
          $this->assertLogMessage('system', "%module module installed.", array('%module' => $module_to_enable), WATCHDOG_INFO);
          $this->assertLogMessage('system', "%module module enabled.", array('%module' => $module_to_enable), WATCHDOG_INFO);
        }

        // Disable and uninstall the original module, and check appropriate
        // hooks, tables, and log messages. (Later, we'll go back and do the
        // same thing for modules that were enabled automatically.) Skip this
        // for the dblog module, because that is needed for the test; we'll go
        // back and do that one at the end also.
        if ($name != 'dblog') {
          $this->assertSuccessfulDisableAndUninstall($name);
        }
      }
    }

    // Go through all modules that were automatically enabled, and try to
    // disable and uninstall them one by one.
    while (!empty($automatically_enabled)) {
      $initial_count = count($automatically_enabled);
      foreach (array_keys($automatically_enabled) as $name) {
        // If the module can't be disabled due to dependencies, skip it and try
        // again the next time. Otherwise, try to disable it.
        $this->drupalGet('admin/modules');
        $disabled_checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Core][' . $name . '][enable]"]');
        if (empty($disabled_checkbox) && $name != 'dblog') {
          unset($automatically_enabled[$name]);
          $this->assertSuccessfulDisableAndUninstall($name);
        }
      }
      $final_count = count($automatically_enabled);
      // If all checkboxes were disabled, something is really wrong with the
      // test. Throw a failure and avoid an infinite loop.
      if ($initial_count == $final_count) {
        $this->fail(t('Remaining modules could not be disabled.'));
        break;
      }
    }

    // Disable and uninstall the dblog module last, since we needed it for
    // assertions in all the above tests.
    if (isset($modules['dblog'])) {
      $this->assertSuccessfulDisableAndUninstall('dblog');
    }

    // Now that all modules have been tested, go back and try to enable them
    // all again at once. This tests two things:
    // - That each module can be successfully enabled again after being
    //   uninstalled.
    // - That enabling more than one module at the same time does not lead to
    //   any errors.
    $edit = array();
    foreach (array_keys($modules) as $name) {
      $edit['modules[Core][' . $name . '][enable]'] = $name;
    }
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
  }

  /**
   * Ensures entity info cache is updated after changes.
   */
  function testEntityInfoChanges() {
    module_enable(array('entity_cache_test'));
    $entity_info = entity_get_info();
    $this->assertTrue(isset($entity_info['entity_cache_test']), 'Test entity type found.');

    // Change the label of the test entity type and make sure changes appear
    // after flushing caches.
    variable_set('entity_cache_test_label', 'New label.');
    drupal_flush_all_caches();
    $info = entity_get_info('entity_cache_test');
    $this->assertEqual($info['label'], 'New label.', 'New label appears in entity info.');

    // Disable the providing module and make sure the entity type is gone.
    module_disable(array('entity_cache_test', 'entity_cache_test_dependency'));
    $entity_info = entity_get_info();
    $this->assertFalse(isset($entity_info['entity_cache_test']), 'Entity type of the providing module is gone.');
  }

  /**
   * Tests entity info cache after enabling a module with a dependency on an entity providing module.
   *
   * @see entity_cache_test_watchdog()
   */
  function testEntityInfoCacheWatchdog() {
    module_enable(array('entity_cache_test'));
    $info = variable_get('entity_cache_test');
    $this->assertEqual($info['label'], 'Entity Cache Test', 'Entity info label is correct.');
    $this->assertEqual($info['controller class'], 'DrupalDefaultEntityController', 'Entity controller class info is correct.');
  }

  /**
   * Disables and uninstalls a module and asserts that it was done correctly.
   *
   * @param $module
   *   The name of the module to disable and uninstall.
   */
  function assertSuccessfulDisableAndUninstall($module) {
    // Disable the module.
    $edit = array();
    $edit['modules[Core][' . $module . '][enable]'] = FALSE;
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
    $this->assertModules(array($module), FALSE);

    // Check that the appropriate hook was fired and the appropriate log
    // message appears.
    $this->assertText(t('hook_modules_disabled fired for @module', array('@module' => $module)));
    $this->assertLogMessage('system', "%module module disabled.", array('%module' => $module), WATCHDOG_INFO);

    //  Check that the module's database tables still exist.
    $this->assertModuleTablesExist($module);

    // Uninstall the module.
    $edit = array();
    $edit['uninstall[' . $module . ']'] = $module;
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
    $this->drupalPost(NULL, NULL, t('Uninstall'));
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
    $this->assertModules(array($module), FALSE);

    // Check that the appropriate hook was fired and the appropriate log
    // message appears. (But don't check for the log message if the dblog
    // module was just uninstalled, since the {watchdog} table won't be there
    // anymore.)
    $this->assertText(t('hook_modules_uninstalled fired for @module', array('@module' => $module)));
    if ($module != 'dblog') {
      $this->assertLogMessage('system', "%module module uninstalled.", array('%module' => $module), WATCHDOG_INFO);
    }

    // Check that the module's database tables no longer exist.
    $this->assertModuleTablesDoNotExist($module);
  }
}

/**
 * Tests failure of hook_requirements('install').
 */
class HookRequirementsTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Requirements hook failure',
      'description' => "Attempts enabling a module that fails hook_requirements('install').",
      'group' => 'Module',
    );
  }

  /**
   * Assert that a module cannot be installed if it fails hook_requirements().
   */
  function testHookRequirementsFailure() {
    $this->assertModules(array('requirements1_test'), FALSE);

    // Attempt to install the requirements1_test module.
    $edit = array();
    $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));

    // Makes sure the module was NOT installed.
    $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
    $this->assertModules(array('requirements1_test'), FALSE);
  }
}

/**
 * Test module dependency functionality.
 */
class ModuleDependencyTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module dependencies',
      'description' => 'Enable module without dependency enabled.',
      'group' => 'Module',
    );
  }

  /**
   * Attempt to enable translation module without locale enabled.
   */
  function testEnableWithoutDependency() {
    // Attempt to enable content translation without locale enabled.
    $edit = array();
    $edit['modules[Core][translation][enable]'] = 'translation';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('Some required modules must be enabled'), 'Dependency required.');

    $this->assertModules(array('translation', 'locale'), FALSE);

    // Assert that the locale tables weren't enabled.
    $this->assertTableCount('languages', FALSE);
    $this->assertTableCount('locale', FALSE);

    $this->drupalPost(NULL, NULL, t('Continue'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');

    $this->assertModules(array('translation', 'locale'), TRUE);

    // Assert that the locale tables were enabled.
    $this->assertTableCount('languages', TRUE);
    $this->assertTableCount('locale', TRUE);
  }

  /**
   * Attempt to enable a module with a missing dependency.
   */
  function testMissingModules() {
    // Test that the system_dependencies_test module is marked
    // as missing a dependency.
    $this->drupalGet('admin/modules');
    $this->assertRaw(t('@module (<span class="admin-missing">missing</span>)', array('@module' => drupal_ucfirst('_missing_dependency'))), 'A module with missing dependencies is marked as such.');
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_dependencies_test][enable]"]');
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');

    // Force enable the system_dependencies_test module.
    module_enable(array('system_dependencies_test'), FALSE);

    // Verify that the module is forced to be disabled when submitting
    // the module page.
    $this->drupalPost('admin/modules', array(), t('Save configuration'));
    $this->assertText(t('The @module module is missing, so the following module will be disabled: @depends.', array('@module' => '_missing_dependency', '@depends' => 'system_dependencies_test')), 'The module missing dependencies will be disabled.');

    // Confirm.
    $this->drupalPost(NULL, NULL, t('Continue'));

    // Verify that the module has been disabled.
    $this->assertModules(array('system_dependencies_test'), FALSE);
  }

  /**
   * Tests enabling a module that depends on an incompatible version of a module.
   */
  function testIncompatibleModuleVersionDependency() {
    // Test that the system_incompatible_module_version_dependencies_test is
    // marked as having an incompatible dependency.
    $this->drupalGet('admin/modules');
    $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> version @version)', array(
      '@module' => 'System incompatible module version test (>2.0)',
      '@version' => '1.0',
    )), 'A module that depends on an incompatible version of a module is marked as such.');
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_module_version_dependencies_test][enable]"]');
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
  }

  /**
   * Tests enabling a module that depends on a module with an incompatible core version.
   */
  function testIncompatibleCoreVersionDependency() {
    // Test that the system_incompatible_core_version_dependencies_test is
    // marked as having an incompatible dependency.
    $this->drupalGet('admin/modules');
    $this->assertRaw(t('@module (<span class="admin-missing">incompatible with</span> this version of Drupal core)', array(
      '@module' => 'System incompatible core version test',
    )), 'A module that depends on a module with an incompatible core version is marked as such.');
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="modules[Testing][system_incompatible_core_version_dependencies_test][enable]"]');
    $this->assert(count($checkbox) == 1, 'Checkbox for the module is disabled.');
  }

  /**
   * Tests enabling a module that depends on a module which fails hook_requirements().
   */
  function testEnableRequirementsFailureDependency() {
    $this->assertModules(array('requirements1_test'), FALSE);
    $this->assertModules(array('requirements2_test'), FALSE);

    // Attempt to install both modules at the same time.
    $edit = array();
    $edit['modules[Testing][requirements1_test][enable]'] = 'requirements1_test';
    $edit['modules[Testing][requirements2_test][enable]'] = 'requirements2_test';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));

    // Makes sure the modules were NOT installed.
    $this->assertText(t('Requirements 1 Test failed requirements'), 'Modules status has been updated.');
    $this->assertModules(array('requirements1_test'), FALSE);
    $this->assertModules(array('requirements2_test'), FALSE);

    // Makes sure that already enabled modules the failing modules depend on
    // were not disabled.
    $this->assertModules(array('comment'), TRUE);

  }

  /**
   * Tests that module dependencies are enabled in the correct order via the
   * UI. Dependencies should be enabled before their dependents.
   */
  function testModuleEnableOrder() {
    module_enable(array('module_test'), FALSE);
    $this->resetAll();
    $this->assertModules(array('module_test'), TRUE);
    variable_set('dependency_test', 'dependency');
    // module_test creates a dependency chain: forum depends on poll, which
    // depends on php. The correct enable order is, php, poll, forum.
    $expected_order = array('php', 'poll', 'forum');

    // Enable the modules through the UI, verifying that the dependency chain
    // is correct.
    $edit = array();
    $edit['modules[Core][forum][enable]'] = 'forum';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertModules(array('forum'), FALSE);
    $this->assertText(t('You must enable the Poll, PHP filter modules to install Forum.'), t('Dependency chain created.'));
    $edit['modules[Core][poll][enable]'] = 'poll';
    $edit['modules[Core][php][enable]'] = 'php';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertModules(array('forum', 'poll', 'php'), TRUE);

    // Check the actual order which is saved by module_test_modules_enabled().
    $this->assertIdentical(variable_get('test_module_enable_order', FALSE), $expected_order, t('Modules enabled in the correct order.'));
  }

  /**
   * Tests attempting to uninstall a module that has installed dependents.
   */
  function testUninstallDependents() {
    // Enable the forum module.
    $edit = array('modules[Core][forum][enable]' => 'forum');
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertModules(array('forum'), TRUE);

    // Disable forum and comment. Both should now be installed but disabled.
    $edit = array('modules[Core][forum][enable]' => FALSE);
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertModules(array('forum'), FALSE);
    $edit = array('modules[Core][comment][enable]' => FALSE);
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertModules(array('comment'), FALSE);

    // Check that the taxonomy module cannot be uninstalled.
    $this->drupalGet('admin/modules/uninstall');
    $checkbox = $this->xpath('//input[@type="checkbox" and @disabled="disabled" and @name="uninstall[comment]"]');
    $this->assert(count($checkbox) == 1, 'Checkbox for uninstalling the comment module is disabled.');

    // Uninstall the forum module, and check that taxonomy now can also be
    // uninstalled.
    $edit = array('uninstall[forum]' => 'forum');
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
    $this->drupalPost(NULL, NULL, t('Uninstall'));
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
    $edit = array('uninstall[comment]' => 'comment');
    $this->drupalPost('admin/modules/uninstall', $edit, t('Uninstall'));
    $this->drupalPost(NULL, NULL, t('Uninstall'));
    $this->assertText(t('The selected modules have been uninstalled.'), 'Modules status has been updated.');
  }
}

/**
 * Test module dependency on specific versions.
 */
class ModuleVersionTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module versions',
      'description' => 'Check module version dependencies.',
      'group' => 'Module',
    );
  }

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

  /**
   * Test version dependencies.
   */
  function testModuleVersions() {
    $dependencies = array(
      // Alternating between being compatible and incompatible with 7.x-2.4-beta3.
      // The first is always a compatible.
      'common_test',
      // Branch incompatibility.
      'common_test (1.x)',
      // Branch compatibility.
      'common_test (2.x)',
      // Another branch incompatibility.
      'common_test (>2.x)',
      // Another branch compatibility.
      'common_test (<=2.x)',
      // Another branch incompatibility.
      'common_test (<2.x)',
      // Another branch compatibility.
      'common_test (>=2.x)',
      // Nonsense, misses a dash. Incompatible with everything.
      'common_test (=7.x2.x, >=2.4)',
      // Core version is optional. Compatible.
      'common_test (=7.x-2.x, >=2.4-alpha2)',
      // Test !=, explicitly incompatible.
      'common_test (=2.x, !=2.4-beta3)',
      // Three operations. Compatible.
      'common_test (=2.x, !=2.3, <2.5)',
      // Testing extra version. Incompatible.
      'common_test (<=2.4-beta2)',
      // Testing extra version. Compatible.
      'common_test (>2.4-beta2)',
      // Testing extra version. Incompatible.
      'common_test (>2.4-rc0)',
    );
    variable_set('dependencies', $dependencies);
    $n = count($dependencies);
    for ($i = 0; $i < $n; $i++) {
      $this->drupalGet('admin/modules');
      $checkbox = $this->xpath('//input[@id="edit-modules-testing-module-test-enable"]');
      $this->assertEqual(!empty($checkbox[0]['disabled']), $i % 2, $dependencies[$i]);
    }
  }
}

/**
 * Test required modules functionality.
 */
class ModuleRequiredTestCase extends ModuleTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Required modules',
      'description' => 'Attempt disabling of required modules.',
      'group' => 'Module',
    );
  }

  /**
   * Assert that core required modules cannot be disabled.
   */
  function testDisableRequired() {
    $module_info = system_get_info('module');
    $this->drupalGet('admin/modules');
    foreach ($module_info as $module => $info) {
      // Check to make sure the checkbox for each required module is disabled
      // and checked (or absent from the page if the module is also hidden).
      if (!empty($info['required'])) {
        $field_name = "modules[{$info['package']}][$module][enable]";
        if (empty($info['hidden'])) {
          $this->assertFieldByXPath("//input[@name='$field_name' and @disabled='disabled' and @checked='checked']", '', format_string('Field @name was disabled and checked.', array('@name' => $field_name)));
        }
        else {
          $this->assertNoFieldByName($field_name);
        }
      }
    }
  }
}

class IPAddressBlockingTestCase extends DrupalWebTestCase {
  protected $blocking_user;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'IP address blocking',
      'description' => 'Test IP address blocking.',
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    // Create user.
    $this->blocking_user = $this->drupalCreateUser(array('block IP addresses'));
    $this->drupalLogin($this->blocking_user);
  }

  /**
   * Test a variety of user input to confirm correct validation and saving of data.
   */
  function testIPAddressValidation() {
    $this->drupalGet('admin/config/people/ip-blocking');

    // Block a valid IP address.
    $edit = array();
    $edit['ip'] = '192.168.1.1';
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $edit['ip']))->fetchField();
    $this->assertTrue($ip, t('IP address found in database.'));
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $edit['ip'])), t('IP address was blocked.'));

    // Try to block an IP address that's already blocked.
    $edit = array();
    $edit['ip'] = '192.168.1.1';
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
    $this->assertText(t('This IP address is already blocked.'));

    // Try to block a reserved IP address.
    $edit = array();
    $edit['ip'] = '255.255.255.255';
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
    $this->assertText(t('Enter a valid IP address.'));

    // Try to block a reserved IP address.
    $edit = array();
    $edit['ip'] = 'test.example.com';
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
    $this->assertText(t('Enter a valid IP address.'));

    // Submit an empty form.
    $edit = array();
    $edit['ip'] = '';
    $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Add'));
    $this->assertText(t('Enter a valid IP address.'));

    // Pass an IP address as a URL parameter and submit it.
    $submit_ip = '1.2.3.4';
    $this->drupalPost('admin/config/people/ip-blocking/' . $submit_ip, NULL, t('Add'));
    $ip = db_query("SELECT iid from {blocked_ips} WHERE ip = :ip", array(':ip' => $submit_ip))->fetchField();
    $this->assertTrue($ip, t('IP address found in database'));
    $this->assertRaw(t('The IP address %ip has been blocked.', array('%ip' => $submit_ip)), t('IP address was blocked.'));

    // Submit your own IP address. This fails, although it works when testing manually.
     // TODO: on some systems this test fails due to a bug or inconsistency in cURL.
     // $edit = array();
     // $edit['ip'] = ip_address();
     // $this->drupalPost('admin/config/people/ip-blocking', $edit, t('Save'));
     // $this->assertText(t('You may not block your own IP address.'));
  }
}

class CronRunTestCase extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Cron run',
      'description' => 'Test cron run.',
      'group' => 'System'
    );
  }

  function setUp() {
    parent::setUp(array('common_test', 'common_test_cron_helper'));
  }

  /**
   * Test cron runs.
   */
  function testCronRun() {
    global $base_url;

    // Run cron anonymously without any cron key.
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE));
    $this->assertResponse(403);

    // Run cron anonymously with a random cron key.
    $key = $this->randomName(16);
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
    $this->assertResponse(403);

    // Run cron anonymously with the valid cron key.
    $key = variable_get('cron_key', 'drupal');
    $this->drupalGet($base_url . '/cron.php', array('external' => TRUE, 'query' => array('cron_key' => $key)));
    $this->assertResponse(200);
  }

  /**
   * Ensure that the automatic cron run feature is working.
   *
   * In these tests we do not use REQUEST_TIME to track start time, because we
   * need the exact time when cron is triggered.
   */
  function testAutomaticCron() {
    // Ensure cron does not run when the cron threshold is enabled and was
    // not passed.
    $cron_last = time();
    $cron_safe_threshold = 100;
    variable_set('cron_last', $cron_last);
    variable_set('cron_safe_threshold', $cron_safe_threshold);
    $this->drupalGet('');
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is not passed.');

    // Test if cron runs when the cron threshold was passed.
    $cron_last = time() - 200;
    variable_set('cron_last', $cron_last);
    $this->drupalGet('');
    sleep(1);
    $this->assertTrue($cron_last < variable_get('cron_last', NULL), 'Cron runs when the cron threshold is passed.');

    // Disable the cron threshold through the interface.
    $admin_user = $this->drupalCreateUser(array('administer site configuration'));
    $this->drupalLogin($admin_user);
    $this->drupalPost('admin/config/system/cron', array('cron_safe_threshold' => 0), t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'));
    $this->drupalLogout();

    // Test if cron does not run when the cron threshold is disabled.
    $cron_last = time() - 200;
    variable_set('cron_last', $cron_last);
    $this->drupalGet('');
    $this->assertTrue($cron_last == variable_get('cron_last', NULL), 'Cron does not run when the cron threshold is disabled.');
  }

  /**
   * Ensure that temporary files are removed.
   *
   * Create files for all the possible combinations of age and status. We are
   * using UPDATE statements rather than file_save() because it would set the
   * timestamp.
   */
  function testTempFileCleanup() {
    // Temporary file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $temp_old = file_save_data('');
    db_update('file_managed')
      ->fields(array(
        'status' => 0,
        'timestamp' => 1,
      ))
      ->condition('fid', $temp_old->fid)
      ->execute();
    $this->assertTrue(file_exists($temp_old->uri), 'Old temp file was created correctly.');

    // Temporary file that is less than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $temp_new = file_save_data('');
    db_update('file_managed')
      ->fields(array('status' => 0))
      ->condition('fid', $temp_new->fid)
      ->execute();
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was created correctly.');

    // Permanent file that is older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $perm_old = file_save_data('');
    db_update('file_managed')
      ->fields(array('timestamp' => 1))
      ->condition('fid', $temp_old->fid)
      ->execute();
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was created correctly.');

    // Permanent file that is newer than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
    $perm_new = file_save_data('');
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was created correctly.');

    // Run cron and then ensure that only the old, temp file was deleted.
    $this->cronRun();
    $this->assertFalse(file_exists($temp_old->uri), 'Old temp file was correctly removed.');
    $this->assertTrue(file_exists($temp_new->uri), 'New temp file was correctly ignored.');
    $this->assertTrue(file_exists($perm_old->uri), 'Old permanent file was correctly ignored.');
    $this->assertTrue(file_exists($perm_new->uri), 'New permanent file was correctly ignored.');
  }

  /**
   * Make sure exceptions thrown on hook_cron() don't affect other modules.
   */
  function testCronExceptions() {
    variable_del('common_test_cron');
    // The common_test module throws an exception. If it isn't caught, the tests
    // won't finish successfully.
    // The common_test_cron_helper module sets the 'common_test_cron' variable.
    $this->cronRun();
    $result = variable_get('common_test_cron');
    $this->assertEqual($result, 'success', 'Cron correctly handles exceptions thrown during hook_cron() invocations.');
  }
}

/**
 * Test execution of the cron queue.
 */
class CronQueueTestCase extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Cron queue functionality',
      'description' => 'Tests the cron queue runner.',
      'group' => 'System'
    );
  }

  function setUp() {
    parent::setUp(array('common_test', 'common_test_cron_helper'));
  }

  /**
   * Tests that exceptions thrown by workers are handled properly.
   */
  function testExceptions() {
    $queue = DrupalQueue::get('cron_queue_test_exception');

    // Enqueue an item for processing.
    $queue->createItem(array($this->randomName() => $this->randomName()));

    // Run cron; the worker for this queue should throw an exception and handle
    // it.
    $this->cronRun();

    // The item should be left in the queue.
    $this->assertEqual($queue->numberOfItems(), 1, 'Failing item still in the queue after throwing an exception.');
  }

}

class AdminMetaTagTestCase extends DrupalWebTestCase {
  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'Fingerprinting meta tag',
      'description' => 'Confirm that the fingerprinting meta tag appears as expected.',
      'group' => 'System'
    );
  }

  /**
   * Verify that the meta tag HTML is generated correctly.
   */
  public function testMetaTag() {
    list($version, ) = explode('.', VERSION);
    $string = '<meta name="Generator" content="Drupal ' . $version . ' (http://drupal.org)" />';
    $this->drupalGet('node');
    $this->assertRaw($string, 'Fingerprinting meta tag generated correctly.', 'System');
  }
}

/**
 * Tests custom access denied functionality.
 */
class AccessDeniedTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => '403 functionality',
      'description' => 'Tests page access denied functionality, including custom 403 pages.',
      'group' => 'System'
    );
  }

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

    // Create an administrative user.
    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'administer site configuration', 'administer blocks'));
  }

  function testAccessDenied() {
    $this->drupalGet('admin');
    $this->assertText(t('Access denied'), 'Found the default 403 page');
    $this->assertResponse(403);

    $this->drupalLogin($this->admin_user);
    $edit = array(
      'title' => $this->randomName(10),
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
    );
    $node = $this->drupalCreateNode($edit);

    // Use a custom 403 page.
    $this->drupalPost('admin/config/system/site-information', array('site_403' => 'node/' . $node->nid), t('Save configuration'));

    $this->drupalLogout();
    $this->drupalGet('admin');
    $this->assertText($node->title, 'Found the custom 403 page');

    // Logout and check that the user login block is shown on custom 403 pages.
    $this->drupalLogout();

    $this->drupalGet('admin');
    $this->assertText($node->title, 'Found the custom 403 page');
    $this->assertText(t('User login'), 'Blocks are shown on the custom 403 page');

    // Log back in and remove the custom 403 page.
    $this->drupalLogin($this->admin_user);
    $this->drupalPost('admin/config/system/site-information', array('site_403' => ''), t('Save configuration'));

    // Logout and check that the user login block is shown on default 403 pages.
    $this->drupalLogout();

    $this->drupalGet('admin');
    $this->assertText(t('Access denied'), 'Found the default 403 page');
    $this->assertResponse(403);
    $this->assertText(t('User login'), 'Blocks are shown on the default 403 page');

    // Log back in, set the custom 403 page to /user and remove the block
    $this->drupalLogin($this->admin_user);
    variable_set('site_403', 'user');
    $this->drupalPost('admin/structure/block', array('blocks[user_login][region]' => '-1'), t('Save blocks'));

    // Check that we can log in from the 403 page.
    $this->drupalLogout();
    $edit = array(
      'name' => $this->admin_user->name,
      'pass' => $this->admin_user->pass_raw,
    );
    $this->drupalPost('admin/config/system/site-information', $edit, t('Log in'));

    // Check that we're still on the same page.
    $this->assertText(t('Site information'));
  }
}

class PageNotFoundTestCase extends DrupalWebTestCase {
  protected $admin_user;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => '404 functionality',
      'description' => "Tests page not found functionality, including custom 404 pages.",
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    // Create an administrative user.
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
    $this->drupalLogin($this->admin_user);
  }

  function testPageNotFound() {
    $this->drupalGet($this->randomName(10));
    $this->assertText(t('Page not found'), 'Found the default 404 page');

    $edit = array(
      'title' => $this->randomName(10),
      'body' => array(LANGUAGE_NONE => array(array('value' => $this->randomName(100)))),
    );
    $node = $this->drupalCreateNode($edit);

    // Use a custom 404 page.
    $this->drupalPost('admin/config/system/site-information', array('site_404' => 'node/' . $node->nid), t('Save configuration'));

    $this->drupalGet($this->randomName(10));
    $this->assertText($node->title, 'Found the custom 404 page');
  }
}

/**
 * Tests site maintenance functionality.
 */
class SiteMaintenanceTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'Site maintenance mode functionality',
      'description' => 'Test access to site while in maintenance mode.',
      'group' => 'System',
    );
  }

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

    // Create a user allowed to access site in maintenance mode.
    $this->user = $this->drupalCreateUser(array('access site in maintenance mode'));
    // Create an administrative user.
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration', 'access site in maintenance mode'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Verify site maintenance mode functionality.
   */
  function testSiteMaintenance() {
    // Turn on maintenance mode.
    $edit = array(
      'maintenance_mode' => 1,
    );
    $this->drupalPost('admin/config/development/maintenance', $edit, t('Save configuration'));

    $admin_message = t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => url('admin/config/development/maintenance')));
    $user_message = t('Operating in maintenance mode.');
    $offline_message = t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')));

    $this->drupalGet('');
    $this->assertRaw($admin_message, 'Found the site maintenance mode message.');

    // Logout and verify that offline message is displayed.
    $this->drupalLogout();
    $this->drupalGet('');
    $this->assertText($offline_message);
    $this->drupalGet('node');
    $this->assertText($offline_message);
    $this->drupalGet('user/register');
    $this->assertText($offline_message);

    // Verify that user is able to log in.
    $this->drupalGet('user');
    $this->assertNoText($offline_message);
    $this->drupalGet('user/login');
    $this->assertNoText($offline_message);

    // Log in user and verify that maintenance mode message is displayed
    // directly after login.
    $edit = array(
      'name' => $this->user->name,
      'pass' => $this->user->pass_raw,
    );
    $this->drupalPost(NULL, $edit, t('Log in'));
    $this->assertText($user_message);

    // Log in administrative user and configure a custom site offline message.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    $this->drupalGet('admin/config/development/maintenance');
    $this->assertNoRaw($admin_message, 'Site maintenance mode message not displayed.');

    $offline_message = 'Sorry, not online.';
    $edit = array(
      'maintenance_mode_message' => $offline_message,
    );
    $this->drupalPost(NULL, $edit, t('Save configuration'));

    // Logout and verify that custom site offline message is displayed.
    $this->drupalLogout();
    $this->drupalGet('');
    $this->assertRaw($offline_message, 'Found the site offline message.');

    // Verify that custom site offline message is not displayed on user/password.
    $this->drupalGet('user/password');
    $this->assertText(t('Username or e-mail address'), 'Anonymous users can access user/password');

    // Submit password reset form.
    $edit = array(
      'name' => $this->user->name,
    );
    $this->drupalPost('user/password', $edit, t('E-mail new password'));
    $mails = $this->drupalGetMails();
    $start = strpos($mails[0]['body'], 'user/reset/'. $this->user->uid);
    $path = substr($mails[0]['body'], $start, 66 + strlen($this->user->uid));

    // Log in with temporary login link.
    $this->drupalPost($path, array(), t('Log in'));
    $this->assertText($user_message);
  }
}

/**
 * Tests generic date and time handling capabilities of Drupal.
 */
class DateTimeFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Date and time',
      'description' => 'Configure date and time settings. Test date formatting and time zone handling, including daylight saving time.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp(array('locale'));

    // Create admin user and log in admin user.
    $this->admin_user = $this->drupalCreateUser(array('administer site configuration'));
    $this->drupalLogin($this->admin_user);
  }


  /**
   * Test time zones and DST handling.
   */
  function testTimeZoneHandling() {
    // Setup date/time settings for Honolulu time.
    variable_set('date_default_timezone', 'Pacific/Honolulu');
    variable_set('configurable_timezones', 0);
    variable_set('date_format_medium', 'Y-m-d H:i:s O');

    // Create some nodes with different authored-on dates.
    $date1 = '2007-01-31 21:00:00 -1000';
    $date2 = '2007-07-31 21:00:00 -1000';
    $node1 = $this->drupalCreateNode(array('created' => strtotime($date1), 'type' => 'article'));
    $node2 = $this->drupalCreateNode(array('created' => strtotime($date2), 'type' => 'article'));

    // Confirm date format and time zone.
    $this->drupalGet("node/$node1->nid");
    $this->assertText('2007-01-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');
    $this->drupalGet("node/$node2->nid");
    $this->assertText('2007-07-31 21:00:00 -1000', 'Date should be identical, with GMT offset of -10 hours.');

    // Set time zone to Los Angeles time.
    variable_set('date_default_timezone', 'America/Los_Angeles');

    // Confirm date format and time zone.
    $this->drupalGet("node/$node1->nid");
    $this->assertText('2007-01-31 23:00:00 -0800', 'Date should be two hours ahead, with GMT offset of -8 hours.');
    $this->drupalGet("node/$node2->nid");
    $this->assertText('2007-08-01 00:00:00 -0700', 'Date should be three hours ahead, with GMT offset of -7 hours.');
  }

  /**
   * Test date type configuration.
   */
  function testDateTypeConfiguration() {
    // Confirm system date types appear.
    $this->drupalGet('admin/config/regional/date-time');
    $this->assertText(t('Medium'), 'System date types appear in date type list.');
    $this->assertNoRaw('href="/admin/config/regional/date-time/types/medium/delete"', 'No delete link appear for system date types.');

    // Add custom date type.
    $this->clickLink(t('Add date type'));
    $date_type = strtolower($this->randomName(8));
    $machine_name = 'machine_' . $date_type;
    $date_format = 'd.m.Y - H:i';
    $edit = array(
      'date_type' => $date_type,
      'machine_name' => $machine_name,
      'date_format' => $date_format,
    );
    $this->drupalPost('admin/config/regional/date-time/types/add', $edit, t('Add date type'));
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertText(t('New date type added successfully.'), 'Date type added confirmation message appears.');
    $this->assertText($date_type, 'Custom date type appears in the date type list.');
    $this->assertText(t('delete'), 'Delete link for custom date type appears.');

    // Delete custom date type.
    $this->clickLink(t('delete'));
    $this->drupalPost('admin/config/regional/date-time/types/' . $machine_name . '/delete', array(), t('Remove'));
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertText(t('Removed date type ' . $date_type), 'Custom date type removed.');
  }

  /**
   * Test date format configuration.
   */
  function testDateFormatConfiguration() {
    // Confirm 'no custom date formats available' message appears.
    $this->drupalGet('admin/config/regional/date-time/formats');
    $this->assertText(t('No custom date formats available.'), 'No custom date formats message appears.');

    // Add custom date format.
    $this->clickLink(t('Add format'));
    $edit = array(
      'date_format' => 'Y',
    );
    $this->drupalPost('admin/config/regional/date-time/formats/add', $edit, t('Add format'));
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertNoText(t('No custom date formats available.'), 'No custom date formats message does not appear.');
    $this->assertText(t('Custom date format added.'), 'Custom date format added.');

    // Ensure custom date format appears in date type configuration options.
    $this->drupalGet('admin/config/regional/date-time');
    $this->assertRaw('<option value="Y">', 'Custom date format appears in options.');

    // Edit custom date format.
    $this->drupalGet('admin/config/regional/date-time/formats');
    $this->clickLink(t('edit'));
    $edit = array(
      'date_format' => 'Y m',
    );
    $this->drupalPost($this->getUrl(), $edit, t('Save format'));
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertText(t('Custom date format updated.'), 'Custom date format successfully updated.');

    // Delete custom date format.
    $this->clickLink(t('delete'));
    $this->drupalPost($this->getUrl(), array(), t('Remove'));
    $this->assertEqual($this->getUrl(), url('admin/config/regional/date-time/formats', array('absolute' => TRUE)), 'Correct page redirection.');
    $this->assertText(t('Removed date format'), 'Custom date format removed successfully.');
  }

  /**
   * Test if the date formats are stored properly.
   */
  function testDateFormatStorage() {
    $date_format = array(
      'type' => 'short',
      'format' => 'dmYHis',
      'locked' => 0,
      'is_new' => 1,
    );
    system_date_format_save($date_format);

    $format = db_select('date_formats', 'df')
      ->fields('df', array('format'))
      ->condition('type', 'short')
      ->condition('format', 'dmYHis')
      ->execute()
      ->fetchField();
    $this->verbose($format);
    $this->assertEqual('dmYHis', $format, 'Unlocalized date format resides in general table.');

    $format = db_select('date_format_locale', 'dfl')
      ->fields('dfl', array('format'))
      ->condition('type', 'short')
      ->condition('format', 'dmYHis')
      ->execute()
      ->fetchField();
    $this->assertFalse($format, 'Unlocalized date format resides not in localized table.');

    // Enable German language
    locale_add_language('de', NULL, NULL, LANGUAGE_LTR, '', '', TRUE, 'en');

    $date_format = array(
      'type' => 'short',
      'format' => 'YMDHis',
      'locales' => array('de', 'tr'),
      'locked' => 0,
      'is_new' => 1,
    );
    system_date_format_save($date_format);

    $format = db_select('date_format_locale', 'dfl')
      ->fields('dfl', array('format'))
      ->condition('type', 'short')
      ->condition('format', 'YMDHis')
      ->condition('language', 'de')
      ->execute()
      ->fetchField();
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in localized table.');

    $format = db_select('date_formats', 'df')
      ->fields('df', array('format'))
      ->condition('type', 'short')
      ->condition('format', 'YMDHis')
      ->execute()
      ->fetchField();
    $this->assertEqual('YMDHis', $format, 'Localized date format resides in general table too.');

    $format = db_select('date_format_locale', 'dfl')
      ->fields('dfl', array('format'))
      ->condition('type', 'short')
      ->condition('format', 'YMDHis')
      ->condition('language', 'tr')
      ->execute()
      ->fetchColumn();
    $this->assertFalse($format, 'Localized date format for disabled language is ignored.');
  }
}

class PageTitleFiltering extends DrupalWebTestCase {
  protected $content_user;
  protected $saved_title;

  /**
   * Implement getInfo().
   */
  public static function getInfo() {
    return array(
      'name' => 'HTML in page titles',
      'description' => 'Tests correct handling or conversion by drupal_set_title() and drupal_get_title() and checks the correct escaping of site name and slogan.',
      'group' => 'System'
    );
  }

  /**
   * Implement setUp().
   */
  function setUp() {
    parent::setUp();

    $this->content_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer themes', 'administer site configuration'));
    $this->drupalLogin($this->content_user);
    $this->saved_title = drupal_get_title();
  }

  /**
   * Reset page title.
   */
  function tearDown() {
    // Restore the page title.
    drupal_set_title($this->saved_title, PASS_THROUGH);

    parent::tearDown();
  }

  /**
   * Tests the handling of HTML by drupal_set_title() and drupal_get_title()
   */
  function testTitleTags() {
    $title = "string with <em>HTML</em>";
    // drupal_set_title's $filter is CHECK_PLAIN by default, so the title should be
    // returned with check_plain().
    drupal_set_title($title, CHECK_PLAIN);
    $this->assertTrue(strpos(drupal_get_title(), '<em>') === FALSE, 'Tags in title converted to entities when $output is CHECK_PLAIN.');
    // drupal_set_title's $filter is passed as PASS_THROUGH, so the title should be
    // returned with HTML.
    drupal_set_title($title, PASS_THROUGH);
    $this->assertTrue(strpos(drupal_get_title(), '<em>') !== FALSE, 'Tags in title are not converted to entities when $output is PASS_THROUGH.');
    // Generate node content.
    $langcode = LANGUAGE_NONE;
    $edit = array(
      "title" => '!SimpleTest! ' . $title . $this->randomName(20),
      "body[$langcode][0][value]" => '!SimpleTest! test body' . $this->randomName(200),
    );
    // Create the node with HTML in the title.
    $this->drupalPost('node/add/page', $edit, t('Save'));

    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $this->assertNotNull($node, 'Node created and found in database');
    $this->drupalGet("node/" . $node->nid);
    $this->assertText(check_plain($edit["title"]), 'Check to make sure tags in the node title are converted.');
  }
  /**
   * Test if the title of the site is XSS proof.
   */
  function testTitleXSS() {
    // Set some title with JavaScript and HTML chars to escape.
    $title = '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ';
    $title_filtered = check_plain($title);

    $slogan = '<script type="text/javascript">alert("Slogan XSS!");</script>';
    $slogan_filtered = filter_xss_admin($slogan);

    // Activate needed appearance settings.
    $edit = array(
      'toggle_name'           => TRUE,
      'toggle_slogan'         => TRUE,
      'toggle_main_menu'      => TRUE,
      'toggle_secondary_menu' => TRUE,
    );
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));

    // Set title and slogan.
    $edit = array(
      'site_name'    => $title,
      'site_slogan'  => $slogan,
    );
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));

    // Load frontpage.
    $this->drupalGet('');

    // Test the title.
    $this->assertNoRaw($title, 'Check for the unfiltered version of the title.');
    // Adding </title> so we do not test the escaped version from drupal_set_title().
    $this->assertRaw($title_filtered . '</title>', 'Check for the filtered version of the title.');

    // Test the slogan.
    $this->assertNoRaw($slogan, 'Check for the unfiltered version of the slogan.');
    $this->assertRaw($slogan_filtered, 'Check for the filtered version of the slogan.');
  }
}

/**
 * Test front page functionality and administration.
 */
class FrontPageTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Front page',
      'description' => 'Tests front page functionality and administration.',
      'group' => 'System',
    );
  }

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

    // Create admin user, log in admin user, and create one node.
    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer site configuration'));
    $this->drupalLogin($this->admin_user);
    $this->node_path = "node/" . $this->drupalCreateNode(array('promote' => 1))->nid;

    // Enable front page logging in system_test.module.
    variable_set('front_page_output', 1);
  }

  /**
   * Test front page functionality.
   */
  function testDrupalIsFrontPage() {
    $this->drupalGet('');
    $this->assertText(t('On front page.'), 'Path is the front page.');
    $this->drupalGet('node');
    $this->assertText(t('On front page.'), 'Path is the front page.');
    $this->drupalGet($this->node_path);
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');

    // Change the front page to an invalid path.
    $edit = array('site_frontpage' => 'kittens');
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
    $this->assertText(t("The path '@path' is either invalid or you do not have access to it.", array('@path' => $edit['site_frontpage'])));

    // Change the front page to a valid path.
    $edit['site_frontpage'] = $this->node_path;
    $this->drupalPost('admin/config/system/site-information', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'The front page path has been saved.');

    $this->drupalGet('');
    $this->assertText(t('On front page.'), 'Path is the front page.');
    $this->drupalGet('node');
    $this->assertNoText(t('On front page.'), 'Path is not the front page.');
    $this->drupalGet($this->node_path);
    $this->assertText(t('On front page.'), 'Path is the front page.');
  }
}

class SystemBlockTestCase extends DrupalWebTestCase {
  protected $profile = 'testing';

  public static function getInfo() {
    return array(
      'name' => 'Block functionality',
      'description' => 'Configure and move powered-by block.',
      'group' => 'System',
    );
  }

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

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

  /**
   * Test displaying and hiding the powered-by and help blocks.
   */
  function testSystemBlocks() {
    // Set block title and some settings to confirm that the interface is available.
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => $this->randomName(8)), t('Save block'));
    $this->assertText(t('The block configuration has been saved.'), t('Block configuration set.'));

    // Set the powered-by block to the footer region.
    $edit = array();
    $edit['blocks[system_powered-by][region]'] = 'footer';
    $edit['blocks[system_main][region]'] = 'content';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->assertText(t('The block settings have been updated.'), t('Block successfully moved to footer region.'));

    // Confirm that the block is being displayed.
    $this->drupalGet('node');
    $this->assertRaw('id="block-system-powered-by"', t('Block successfully being displayed on the page.'));

    // Set the block to the disabled region.
    $edit = array();
    $edit['blocks[system_powered-by][region]'] = '-1';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));

    // Confirm that the block is hidden.
    $this->assertNoRaw('id="block-system-powered-by"', t('Block no longer appears on page.'));

    // For convenience of developers, set the block to its default settings.
    $edit = array();
    $edit['blocks[system_powered-by][region]'] = 'footer';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
    $this->drupalPost('admin/structure/block/manage/system/powered-by/configure', array('title' => ''), t('Save block'));

    // Set the help block to the help region.
    $edit = array();
    $edit['blocks[system_help][region]'] = 'help';
    $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));

    // Test displaying the help block with block caching enabled.
    variable_set('block_cache', TRUE);
    $this->drupalGet('admin/structure/block/add');
    $this->assertRaw(t('Use this page to create a new custom block.'));
    $this->drupalGet('admin/index');
    $this->assertRaw(t('This page shows you all available administration tasks for each module.'));
  }
}

/**
 * Test main content rendering fallback provided by system module.
 */
class SystemMainContentFallback extends DrupalWebTestCase {
  protected $admin_user;
  protected $web_user;

  public static function getInfo() {
    return array(
      'name' => 'Main content rendering fallback',
      'description' => ' Test system module main content rendering fallback.',
      'group' => 'System',
    );
  }

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

    // Create and login admin user.
    $this->admin_user = $this->drupalCreateUser(array(
      'access administration pages',
      'administer site configuration',
      'administer modules',
      'administer blocks',
      'administer nodes',
    ));
    $this->drupalLogin($this->admin_user);

    // Create a web user.
    $this->web_user = $this->drupalCreateUser(array('access user profiles', 'access content'));
  }

  /**
   * Test availability of main content.
   */
  function testMainContentFallback() {
    $edit = array();
    // Disable the dashboard module, which depends on the block module.
    $edit['modules[Core][dashboard][enable]'] = FALSE;
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
    // Disable the block module.
    $edit['modules[Core][block][enable]'] = FALSE;
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
    module_list(TRUE);
    $this->assertFalse(module_exists('block'), 'Block module disabled.');

    // At this point, no region is filled and fallback should be triggered.
    $this->drupalGet('admin/config/system/site-information');
    $this->assertField('site_name', 'Admin interface still available.');

    // Fallback should not trigger when another module is handling content.
    $this->drupalGet('system-test/main-content-handling');
    $this->assertRaw('id="system-test-content"', 'Content handled by another module');
    $this->assertText(t('Content to test main content fallback'), 'Main content still displayed.');

    // Fallback should trigger when another module
    // indicates that it is not handling the content.
    $this->drupalGet('system-test/main-content-fallback');
    $this->assertText(t('Content to test main content fallback'), 'Main content fallback properly triggers.');

    // Fallback should not trigger when another module is handling content.
    // Note that this test ensures that no duplicate
    // content gets created by the fallback.
    $this->drupalGet('system-test/main-content-duplication');
    $this->assertNoText(t('Content to test main content fallback'), 'Main content not duplicated.');

    // Request a user* page and see if it is displayed.
    $this->drupalLogin($this->web_user);
    $this->drupalGet('user/' . $this->web_user->uid . '/edit');
    $this->assertField('mail', 'User interface still available.');

    // Enable the block module again.
    $this->drupalLogin($this->admin_user);
    $edit = array();
    $edit['modules[Core][block][enable]'] = 'block';
    $this->drupalPost('admin/modules', $edit, t('Save configuration'));
    $this->assertText(t('The configuration options have been saved.'), 'Modules status has been updated.');
    module_list(TRUE);
    $this->assertTrue(module_exists('block'), 'Block module re-enabled.');
  }
}

/**
 * Tests for the theme interface functionality.
 */
class SystemThemeFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Theme interface functionality',
      'description' => 'Tests the theme interface functionality by enabling and switching themes, and using an administration theme.',
      'group' => 'System',
    );
  }

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

    $this->admin_user = $this->drupalCreateUser(array('access administration pages', 'view the administration theme', 'administer themes', 'bypass node access', 'administer blocks'));
    $this->drupalLogin($this->admin_user);
    $this->node = $this->drupalCreateNode();
  }

  /**
   * Test the theme settings form.
   */
  function testThemeSettings() {
    // Specify a filesystem path to be used for the logo.
    $file = current($this->drupalGetTestFiles('image'));
    $file_relative = strtr($file->uri, array('public:/' => variable_get('file_public_path', conf_path() . '/files')));
    $default_theme_path = 'themes/stark';

    $supported_paths = array(
      // Raw stream wrapper URI.
      $file->uri => array(
        'form' => file_uri_target($file->uri),
        'src' => file_create_url($file->uri),
      ),
      // Relative path within the public filesystem.
      file_uri_target($file->uri) => array(
        'form' => file_uri_target($file->uri),
        'src' => file_create_url($file->uri),
      ),
      // Relative path to a public file.
      $file_relative => array(
        'form' => $file_relative,
        'src' => file_create_url($file->uri),
      ),
      // Relative path to an arbitrary file.
      'misc/druplicon.png' => array(
        'form' => 'misc/druplicon.png',
        'src' => $GLOBALS['base_url'] . '/' . 'misc/druplicon.png',
      ),
      // Relative path to a file in a theme.
      $default_theme_path . '/logo.png' => array(
        'form' => $default_theme_path . '/logo.png',
        'src' => $GLOBALS['base_url'] . '/' . $default_theme_path . '/logo.png',
      ),
    );
    foreach ($supported_paths as $input => $expected) {
      $edit = array(
        'default_logo' => FALSE,
        'logo_path' => $input,
      );
      $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));
      $this->assertNoText('The custom logo path is invalid.');
      $this->assertFieldByName('logo_path', $expected['form']);

      // Verify the actual 'src' attribute of the logo being output.
      $this->drupalGet('');
      $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
      $this->assertEqual((string) $elements[0]['src'], $expected['src']);
    }

    $unsupported_paths = array(
      // Stream wrapper URI to non-existing file.
      'public://whatever.png',
      'private://whatever.png',
      'temporary://whatever.png',
      // Bogus stream wrapper URIs.
      'public:/whatever.png',
      '://whatever.png',
      ':whatever.png',
      'public://',
      // Relative path within the public filesystem to non-existing file.
      'whatever.png',
      // Relative path to non-existing file in public filesystem.
      variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
      // Semi-absolute path to non-existing file in public filesystem.
      '/' . variable_get('file_public_path', conf_path() . '/files') . '/whatever.png',
      // Relative path to arbitrary non-existing file.
      'misc/whatever.png',
      // Semi-absolute path to arbitrary non-existing file.
      '/misc/whatever.png',
      // Absolute paths to any local file (even if it exists).
      drupal_realpath($file->uri),
    );
    $this->drupalGet('admin/appearance/settings');
    foreach ($unsupported_paths as $path) {
      $edit = array(
        'default_logo' => FALSE,
        'logo_path' => $path,
      );
      $this->drupalPost(NULL, $edit, t('Save configuration'));
      $this->assertText('The custom logo path is invalid.');
    }

    // Upload a file to use for the logo.
    $edit = array(
      'default_logo' => FALSE,
      'logo_path' => '',
      'files[logo_upload]' => drupal_realpath($file->uri),
    );
    $this->drupalPost('admin/appearance/settings', $edit, t('Save configuration'));

    $fields = $this->xpath($this->constructFieldXpath('name', 'logo_path'));
    $uploaded_filename = 'public://' . $fields[0]['value'];

    $this->drupalGet('');
    $elements = $this->xpath('//*[@id=:id]/img', array(':id' => 'logo'));
    $this->assertEqual($elements[0]['src'], file_create_url($uploaded_filename));
  }

  /**
   * Test the administration theme functionality.
   */
  function testAdministrationTheme() {
    theme_enable(array('stark'));
    variable_set('theme_default', 'stark');
    // Enable an administration theme and show it on the node admin pages.
    $edit = array(
      'admin_theme' => 'seven',
      'node_admin_theme' => TRUE,
    );
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));

    $this->drupalGet('admin/config');
    $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');

    $this->drupalGet('node/' . $this->node->nid);
    $this->assertRaw('themes/stark', 'Site default theme used on node page.');

    $this->drupalGet('node/add');
    $this->assertRaw('themes/seven', 'Administration theme used on the add content page.');

    $this->drupalGet('node/' . $this->node->nid . '/edit');
    $this->assertRaw('themes/seven', 'Administration theme used on the edit content page.');

    // Disable the admin theme on the node admin pages.
    $edit = array(
      'node_admin_theme' => FALSE,
    );
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));

    $this->drupalGet('admin/config');
    $this->assertRaw('themes/seven', 'Administration theme used on an administration page.');

    $this->drupalGet('node/add');
    $this->assertRaw('themes/stark', 'Site default theme used on the add content page.');

    // Reset to the default theme settings.
    variable_set('theme_default', 'bartik');
    $edit = array(
      'admin_theme' => '0',
      'node_admin_theme' => FALSE,
    );
    $this->drupalPost('admin/appearance', $edit, t('Save configuration'));

    $this->drupalGet('admin');
    $this->assertRaw('themes/bartik', 'Site default theme used on administration page.');

    $this->drupalGet('node/add');
    $this->assertRaw('themes/bartik', 'Site default theme used on the add content page.');
  }

  /**
   * Test switching the default theme.
   */
  function testSwitchDefaultTheme() {
    // Enable "stark" and set it as the default theme.
    theme_enable(array('stark'));
    $this->drupalGet('admin/appearance');
    $this->clickLink(t('Set default'), 1);
    $this->assertTrue(variable_get('theme_default', '') == 'stark', 'Site default theme switched successfully.');

    // Test the default theme on the secondary links (blocks admin page).
    $this->drupalGet('admin/structure/block');
    $this->assertText('Stark(' . t('active tab') . ')', 'Default local task on blocks admin page is the default theme.');
    // Switch back to Bartik and test again to test that the menu cache is cleared.
    $this->drupalGet('admin/appearance');
    $this->clickLink(t('Set default'), 0);
    $this->drupalGet('admin/structure/block');
    $this->assertText('Bartik(' . t('active tab') . ')', 'Default local task on blocks admin page has changed.');
  }
}


/**
 * Test the basic queue functionality.
 */
class QueueTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Queue functionality',
      'description' => 'Queues and dequeues a set of items to check the basic queue functionality.',
      'group' => 'System',
    );
  }

  /**
   * Queues and dequeues a set of items to check the basic queue functionality.
   */
  function testQueue() {
    // Create two queues.
    $queue1 = DrupalQueue::get($this->randomName());
    $queue1->createQueue();
    $queue2 = DrupalQueue::get($this->randomName());
    $queue2->createQueue();

    // Create four items.
    $data = array();
    for ($i = 0; $i < 4; $i++) {
      $data[] = array($this->randomName() => $this->randomName());
    }

    // Queue items 1 and 2 in the queue1.
    $queue1->createItem($data[0]);
    $queue1->createItem($data[1]);

    // Retrieve two items from queue1.
    $items = array();
    $new_items = array();

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    // First two dequeued items should match the first two items we queued.
    $this->assertEqual($this->queueScore($data, $new_items), 2, 'Two items matched');

    // Add two more items.
    $queue1->createItem($data[2]);
    $queue1->createItem($data[3]);

    $this->assertTrue($queue1->numberOfItems(), 'Queue 1 is not empty after adding items.');
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty while Queue 1 has items');

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    $items[] = $item = $queue1->claimItem();
    $new_items[] = $item->data;

    // All dequeued items should match the items we queued exactly once,
    // therefore the score must be exactly 4.
    $this->assertEqual($this->queueScore($data, $new_items), 4, 'Four items matched');

    // There should be no duplicate items.
    $this->assertEqual($this->queueScore($new_items, $new_items), 4, 'Four items matched');

    // Delete all items from queue1.
    foreach ($items as $item) {
      $queue1->deleteItem($item);
    }

    // Check that both queues are empty.
    $this->assertFalse($queue1->numberOfItems(), 'Queue 1 is empty');
    $this->assertFalse($queue2->numberOfItems(), 'Queue 2 is empty');
  }

  /**
   * This function returns the number of equal items in two arrays.
   */
  function queueScore($items, $new_items) {
    $score = 0;
    foreach ($items as $item) {
      foreach ($new_items as $new_item) {
        if ($item === $new_item) {
          $score++;
        }
      }
    }
    return $score;
  }
}

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

  /**
   * Creates a user and a node, then tests the tokens generated from them.
   */
  function testTokenReplacement() {
    // Create the initial objects.
    $account = $this->drupalCreateUser();
    $node = $this->drupalCreateNode(array('uid' => $account->uid));
    $node->title = '<blink>Blinking Text</blink>';
    global $user, $language;

    $source  = '[node:title]';         // Title of the node we passed in
    $source .= '[node:author:name]';   // Node author's name
    $source .= '[node:created:since]'; // Time since the node was created
    $source .= '[current-user:name]';  // Current user's name
    $source .= '[date:short]';         // Short date format of REQUEST_TIME
    $source .= '[user:name]';          // No user passed in, should be untouched
    $source .= '[bogus:token]';        // Non-existent token

    $target  = check_plain($node->title);
    $target .= check_plain($account->name);
    $target .= format_interval(REQUEST_TIME - $node->created, 2, $language->language);
    $target .= check_plain($user->name);
    $target .= format_date(REQUEST_TIME, 'short', '', NULL, $language->language);

    // Test that the clear parameter cleans out non-existent tokens.
    $result = token_replace($source, array('node' => $node), array('language' => $language, 'clear' => TRUE));
    $result = $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens cleared out.');

    // Test without using the clear parameter (non-existent token untouched).
    $target .= '[user:name]';
    $target .= '[bogus:token]';
    $result = token_replace($source, array('node' => $node), array('language' => $language));
    $this->assertEqual($target, $result, 'Valid tokens replaced while invalid tokens ignored.');

    // Check that the results of token_generate are sanitized properly. This does NOT
    // test the cleanliness of every token -- just that the $sanitize flag is being
    // passed properly through the call stack and being handled correctly by a 'known'
    // token, [node:title].
    $raw_tokens = array('title' => '[node:title]');
    $generated = token_generate('node', $raw_tokens, array('node' => $node));
    $this->assertEqual($generated['[node:title]'], check_plain($node->title), 'Token sanitized.');

    $generated = token_generate('node', $raw_tokens, array('node' => $node), array('sanitize' => FALSE));
    $this->assertEqual($generated['[node:title]'], $node->title, 'Unsanitized token generated properly.');

    // Test token replacement when the string contains no tokens.
    $this->assertEqual(token_replace('No tokens here.'), 'No tokens here.');
  }

  /**
   * Test whether token-replacement works in various contexts.
   */
  function testSystemTokenRecognition() {
    global $language;

    // Generate prefixes and suffixes for the token context.
    $tests = array(
      array('prefix' => 'this is the ', 'suffix' => ' site'),
      array('prefix' => 'this is the', 'suffix' => 'site'),
      array('prefix' => '[', 'suffix' => ']'),
      array('prefix' => '', 'suffix' => ']]]'),
      array('prefix' => '[[[', 'suffix' => ''),
      array('prefix' => ':[:', 'suffix' => '--]'),
      array('prefix' => '-[-', 'suffix' => ':]:'),
      array('prefix' => '[:', 'suffix' => ']'),
      array('prefix' => '[site:', 'suffix' => ':name]'),
      array('prefix' => '[site:', 'suffix' => ']'),
    );

    // Check if the token is recognized in each of the contexts.
    foreach ($tests as $test) {
      $input = $test['prefix'] . '[site:name]' . $test['suffix'];
      $expected = $test['prefix'] . 'Drupal' . $test['suffix'];
      $output = token_replace($input, array(), array('language' => $language));
      $this->assertTrue($output == $expected, format_string('Token recognized in string %string', array('%string' => $input)));
    }
  }

  /**
   * Tests the generation of all system site information tokens.
   */
  function testSystemSiteTokenReplacement() {
    global $language;
    $url_options = array(
      'absolute' => TRUE,
      'language' => $language,
    );

    // Set a few site variables.
    variable_set('site_name', '<strong>Drupal<strong>');
    variable_set('site_slogan', '<blink>Slogan</blink>');

    // Generate and test sanitized tokens.
    $tests = array();
    $tests['[site:name]'] = check_plain(variable_get('site_name', 'Drupal'));
    $tests['[site:slogan]'] = check_plain(variable_get('site_slogan', ''));
    $tests['[site:mail]'] = 'simpletest@example.com';
    $tests['[site:url]'] = url('<front>', $url_options);
    $tests['[site:url-brief]'] = preg_replace(array('!^https?://!', '!/$!'), '', url('<front>', $url_options));
    $tests['[site:login-url]'] = url('user', $url_options);

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

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

    // Generate and test unsanitized tokens.
    $tests['[site:name]'] = variable_get('site_name', 'Drupal');
    $tests['[site:slogan]'] = variable_get('site_slogan', '');

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

  /**
   * Tests the generation of all system date tokens.
   */
  function testSystemDateTokenReplacement() {
    global $language;

    // Set time to one hour before request.
    $date = REQUEST_TIME - 3600;

    // Generate and test tokens.
    $tests = array();
    $tests['[date:short]'] = format_date($date, 'short', '', NULL, $language->language);
    $tests['[date:medium]'] = format_date($date, 'medium', '', NULL, $language->language);
    $tests['[date:long]'] = format_date($date, 'long', '', NULL, $language->language);
    $tests['[date:custom:m/j/Y]'] = format_date($date, 'custom', 'm/j/Y', NULL, $language->language);
    $tests['[date:since]'] = format_interval((REQUEST_TIME - $date), 2, $language->language);
    $tests['[date:raw]'] = filter_xss($date);

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

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

class InfoFileParserTestCase extends DrupalUnitTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Info file format parser',
      'description' => 'Tests proper parsing of a .info file formatted string.',
      'group' => 'System',
    );
  }

  /**
   * Test drupal_parse_info_format().
   */
  function testDrupalParseInfoFormat() {
    $config = '
simple = Value
quoted = " Value"
multiline = "Value
  Value"
array[] = Value1
array[] = Value2
array_assoc[a] = Value1
array_assoc[b] = Value2
array_deep[][][] = Value
array_deep_assoc[a][b][c] = Value
array_space[a b] = Value';

    $expected = array(
      'simple' => 'Value',
      'quoted' => ' Value',
      'multiline' => "Value\n  Value",
      'array' => array(
        0 => 'Value1',
        1 => 'Value2',
      ),
      'array_assoc' => array(
        'a' => 'Value1',
        'b' => 'Value2',
      ),
      'array_deep' => array(
        0 => array(
          0 => array(
            0 => 'Value',
          ),
        ),
      ),
      'array_deep_assoc' => array(
        'a' => array(
          'b' => array(
            'c' => 'Value',
          ),
        ),
      ),
      'array_space' => array(
        'a b' => 'Value',
      ),
    );

    $parsed = drupal_parse_info_format($config);

    $this->assertEqual($parsed['simple'], $expected['simple'], 'Set a simple value.');
    $this->assertEqual($parsed['quoted'], $expected['quoted'], 'Set a simple value in quotes.');
    $this->assertEqual($parsed['multiline'], $expected['multiline'], 'Set a multiline value.');
    $this->assertEqual($parsed['array'], $expected['array'], 'Set a simple array.');
    $this->assertEqual($parsed['array_assoc'], $expected['array_assoc'], 'Set an associative array.');
    $this->assertEqual($parsed['array_deep'], $expected['array_deep'], 'Set a nested array.');
    $this->assertEqual($parsed['array_deep_assoc'], $expected['array_deep_assoc'], 'Set a nested associative array.');
    $this->assertEqual($parsed['array_space'], $expected['array_space'], 'Set an array with a whitespace in the key.');
    $this->assertEqual($parsed, $expected, 'Entire parsed .info string and expected array are identical.');
  }
}

/**
 * Tests the effectiveness of hook_system_info_alter().
 */
class SystemInfoAlterTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'System info alter',
      'description' => 'Tests the effectiveness of hook_system_info_alter().',
      'group' => 'System',
    );
  }

  /**
   * Tests that {system}.info is rebuilt after a module that implements
   * hook_system_info_alter() is enabled. Also tests if core *_list() functions
   * return freshly altered info.
   */
  function testSystemInfoAlter() {
    // Enable our test module. Flush all caches, which we assert is the only
    // thing necessary to use the rebuilt {system}.info.
    module_enable(array('module_test'), FALSE);
    drupal_flush_all_caches();
    $this->assertTrue(module_exists('module_test'), 'Test module is enabled.');

    $info = $this->getSystemInfo('seven', 'theme');
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was added to {system}.info.');
    $seven_regions = system_region_list('seven');
    $this->assertTrue(isset($seven_regions['test_region']), 'Altered theme info was returned by system_region_list().');
    $system_list_themes = system_list('theme');
    $info = $system_list_themes['seven']->info;
    $this->assertTrue(isset($info['regions']['test_region']), 'Altered theme info was returned by system_list().');
    $list_themes = list_themes();
    $this->assertTrue(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was returned by list_themes().');

    // Disable the module and verify that {system}.info is rebuilt without it.
    module_disable(array('module_test'), FALSE);
    drupal_flush_all_caches();
    $this->assertFalse(module_exists('module_test'), 'Test module is disabled.');

    $info = $this->getSystemInfo('seven', 'theme');
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was removed from {system}.info.');
    $seven_regions = system_region_list('seven');
    $this->assertFalse(isset($seven_regions['test_region']), 'Altered theme info was not returned by system_region_list().');
    $system_list_themes = system_list('theme');
    $info = $system_list_themes['seven']->info;
    $this->assertFalse(isset($info['regions']['test_region']), 'Altered theme info was not returned by system_list().');
    $list_themes = list_themes();
    $this->assertFalse(isset($list_themes['seven']->info['regions']['test_region']), 'Altered theme info was not returned by list_themes().');
  }

  /**
   * Returns the info array as it is stored in {system}.
   *
   * @param $name
   *   The name of the record in {system}.
   * @param $type
   *   The type of record in {system}.
   *
   * @return
   *   Array of info, or FALSE if the record is not found.
   */
  function getSystemInfo($name, $type) {
    $raw_info = db_query("SELECT info FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
    return $raw_info ? unserialize($raw_info) : FALSE;
  }
}

/**
 * Tests for the update system functionality.
 */
class UpdateScriptFunctionalTest extends DrupalWebTestCase {
  private $update_url;
  private $update_user;

  public static function getInfo() {
    return array(
      'name' => 'Update functionality',
      'description' => 'Tests the update script access and functionality.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp('update_script_test');
    $this->update_url = $GLOBALS['base_url'] . '/update.php';
    $this->update_user = $this->drupalCreateUser(array('administer software updates'));
  }

  /**
   * Tests access to the update script.
   */
  function testUpdateAccess() {
    // Try accessing update.php without the proper permission.
    $regular_user = $this->drupalCreateUser();
    $this->drupalLogin($regular_user);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertResponse(403);

    // Try accessing update.php as an anonymous user.
    $this->drupalLogout();
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertResponse(403);

    // Access the update page with the proper permission.
    $this->drupalLogin($this->update_user);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertResponse(200);

    // Access the update page as user 1.
    $user1 = user_load(1);
    $user1->pass_raw = user_password();
    require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
    $user1->pass = user_hash_password(trim($user1->pass_raw));
    db_query("UPDATE {users} SET pass = :pass WHERE uid = :uid", array(':pass' => $user1->pass, ':uid' => $user1->uid));
    $this->drupalLogin($user1);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertResponse(200);
  }

  /**
   * Tests that requirements warnings and errors are correctly displayed.
   */
  function testRequirements() {
    $this->drupalLogin($this->update_user);

    // If there are no requirements warnings or errors, we expect to be able to
    // go through the update process uninterrupted.
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->drupalPost(NULL, array(), t('Continue'));
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
    // Confirm that all caches were cleared.
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared when there were no requirements warnings or errors.');

    // If there is a requirements warning, we expect it to be initially
    // displayed, but clicking the link to proceed should allow us to go
    // through the rest of the update process uninterrupted.

    // First, run this test with pending updates to make sure they can be run
    // successfully.
    variable_set('update_script_test_requirement_type', REQUIREMENT_WARNING);
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
    $this->clickLink('try again');
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
    $this->drupalPost(NULL, array(), t('Continue'));
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
    $this->assertText(t('The update_script_test_update_7000() update was executed successfully.'), 'End of update process was reached.');
    // Confirm that all caches were cleared.
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after resolving a requirements warning and applying updates.');

    // Now try again without pending updates to make sure that works too.
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertText('This is a requirements warning provided by the update_script_test module.');
    $this->clickLink('try again');
    $this->assertNoText('This is a requirements warning provided by the update_script_test module.');
    $this->drupalPost(NULL, array(), t('Continue'));
    $this->assertText(t('No pending updates.'), 'End of update process was reached.');
    // Confirm that all caches were cleared.
    $this->assertText(t('hook_flush_caches() invoked for update_script_test.module.'), 'Caches were cleared after applying updates and re-running the script.');

    // If there is a requirements error, it should be displayed even after
    // clicking the link to proceed (since the problem that triggered the error
    // has not been fixed).
    variable_set('update_script_test_requirement_type', REQUIREMENT_ERROR);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $this->assertText('This is a requirements error provided by the update_script_test module.');
    $this->clickLink('try again');
    $this->assertText('This is a requirements error provided by the update_script_test module.');
  }

  /**
   * Tests the effect of using the update script on the theme system.
   */
  function testThemeSystem() {
    // Since visiting update.php triggers a rebuild of the theme system from an
    // unusual maintenance mode environment, we check that this rebuild did not
    // put any incorrect information about the themes into the database.
    $original_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
    $this->drupalLogin($this->update_user);
    $this->drupalGet($this->update_url, array('external' => TRUE));
    $final_theme_data = db_query("SELECT * FROM {system} WHERE type = 'theme' ORDER BY name")->fetchAll();
    $this->assertEqual($original_theme_data, $final_theme_data, 'Visiting update.php does not alter the information about themes stored in the database.');
  }

  /**
   * Tests update.php when there are no updates to apply.
   */
  function testNoUpdateFunctionality() {
    // Click through update.php with 'administer software updates' permission.
    $this->drupalLogin($this->update_user);
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
    $this->assertText(t('No pending updates.'));
    $this->assertNoLink('Administration pages');
    $this->clickLink('Front page');
    $this->assertResponse(200);

    // Click through update.php with 'access administration pages' permission.
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages'));
    $this->drupalLogin($admin_user);
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
    $this->assertText(t('No pending updates.'));
    $this->clickLink('Administration pages');
    $this->assertResponse(200);
  }

  /**
   * Tests update.php after performing a successful update.
   */
  function testSuccessfulUpdateFunctionality() {
    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
    // Click through update.php with 'administer software updates' permission.
    $this->drupalLogin($this->update_user);
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
    $this->assertText('Updates were attempted.');
    $this->assertLink('site');
    $this->assertNoLink('Administration pages');
    $this->assertNoLink('logged');
    $this->clickLink('Front page');
    $this->assertResponse(200);

    drupal_set_installed_schema_version('update_script_test', drupal_get_installed_schema_version('update_script_test') - 1);
    // Click through update.php with 'access administration pages' and
    // 'access site reports' permissions.
    $admin_user = $this->drupalCreateUser(array('administer software updates', 'access administration pages', 'access site reports'));
    $this->drupalLogin($admin_user);
    $this->drupalPost($this->update_url, array(), t('Continue'), array('external' => TRUE));
    $this->drupalPost(NULL, array(), t('Apply pending updates'));
    $this->assertText('Updates were attempted.');
    $this->assertLink('logged');
    $this->clickLink('Administration pages');
    $this->assertResponse(200);
  }
}

/**
 * Functional tests for the flood control mechanism.
 */
class FloodFunctionalTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Flood control mechanism',
      'description' => 'Functional tests for the flood control mechanism.',
      'group' => 'System',
    );
  }

  /**
   * Test flood control mechanism clean-up.
   */
  function testCleanUp() {
    $threshold = 1;
    $window_expired = -1;
    $name = 'flood_test_cleanup';

    // Register expired event.
    flood_register_event($name, $window_expired);
    // Verify event is not allowed.
    $this->assertFalse(flood_is_allowed($name, $threshold));
    // Run cron and verify event is now allowed.
    $this->cronRun();
    $this->assertTrue(flood_is_allowed($name, $threshold));

    // Register unexpired event.
    flood_register_event($name);
    // Verify event is not allowed.
    $this->assertFalse(flood_is_allowed($name, $threshold));
    // Run cron and verify event is still not allowed.
    $this->cronRun();
    $this->assertFalse(flood_is_allowed($name, $threshold));
  }
}

/**
 * Test HTTP file downloading capability.
 */
class RetrieveFileTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'HTTP file retrieval',
      'description' => 'Checks HTTP file fetching and error handling.',
      'group' => 'System',
    );
  }

  /**
   * Invokes system_retrieve_file() in several scenarios.
   */
  function testFileRetrieving() {
    // Test 404 handling by trying to fetch a randomly named file.
    drupal_mkdir($sourcedir = 'public://' . $this->randomName());
    $filename = 'Файл для тестирования ' . $this->randomName();
    $url = file_create_url($sourcedir . '/' . $filename);
    $retrieved_file = system_retrieve_file($url);
    $this->assertFalse($retrieved_file, 'Non-existent file not fetched.');

    // Actually create that file, download it via HTTP and test the returned path.
    file_put_contents($sourcedir . '/' . $filename, 'testing');
    $retrieved_file = system_retrieve_file($url);

    // URLs could not contains characters outside the ASCII set so $filename
    // has to be encoded.
    $encoded_filename = rawurlencode($filename);

    $this->assertEqual($retrieved_file, 'public://' . $encoded_filename, 'Sane path for downloaded file returned (public:// scheme).');
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (public:// scheme).');
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (public:// scheme).');
    file_unmanaged_delete($retrieved_file);

    // Test downloading file to a different location.
    drupal_mkdir($targetdir = 'temporary://' . $this->randomName());
    $retrieved_file = system_retrieve_file($url, $targetdir);
    $this->assertEqual($retrieved_file, "$targetdir/$encoded_filename", 'Sane path for downloaded file returned (temporary:// scheme).');
    $this->assertTrue(is_file($retrieved_file), 'Downloaded file does exist (temporary:// scheme).');
    $this->assertEqual(filesize($retrieved_file), 7, 'File size of downloaded file is correct (temporary:// scheme).');
    file_unmanaged_delete($retrieved_file);

    file_unmanaged_delete_recursive($sourcedir);
    file_unmanaged_delete_recursive($targetdir);
  }
}

/**
 * Functional tests shutdown functions.
 */
class ShutdownFunctionsTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Shutdown functions',
      'description' => 'Functional tests for shutdown functions',
      'group' => 'System',
    );
  }

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

  /**
   * Test shutdown functions.
   */
  function testShutdownFunctions() {
    $arg1 = $this->randomName();
    $arg2 = $this->randomName();
    $this->drupalGet('system-test/shutdown-functions/' . $arg1 . '/' . $arg2);
    $this->assertText(t('First shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));
    $this->assertText(t('Second shutdown function, arg1 : @arg1, arg2: @arg2', array('@arg1' => $arg1, '@arg2' => $arg2)));

    // Make sure exceptions displayed through _drupal_render_exception_safe()
    // are correctly escaped.
    $this->assertRaw('Drupal is &amp;lt;blink&amp;gt;awesome&amp;lt;/blink&amp;gt;.');
  }
}

/**
 * Tests administrative overview pages.
 */
class SystemAdminTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Administrative pages',
      'description' => 'Tests output on administrative pages and compact mode functionality.',
      'group' => 'System',
    );
  }

  function setUp() {
    // testAdminPages() requires Locale module.
    parent::setUp(array('locale'));

    // Create an administrator with all permissions, as well as a regular user
    // who can only access administration pages and perform some Locale module
    // administrative tasks, but not all of them.
    $this->admin_user = $this->drupalCreateUser(array_keys(module_invoke_all('permission')));
    $this->web_user = $this->drupalCreateUser(array(
      'access administration pages',
      'translate interface',
    ));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Tests output on administrative listing pages.
   */
  function testAdminPages() {
    // Go to Administration.
    $this->drupalGet('admin');

    // Verify that all visible, top-level administration links are listed on
    // the main administration page.
    foreach (menu_get_router() as $path => $item) {
      if (strpos($path, 'admin/') === 0 && ($item['type'] & MENU_VISIBLE_IN_TREE) && $item['_number_parts'] == 2) {
        $this->assertLink($item['title']);
        $this->assertLinkByHref($path);
        $this->assertText($item['description']);
      }
    }

    // For each administrative listing page on which the Locale module appears,
    // verify that there are links to the module's primary configuration pages,
    // but no links to its individual sub-configuration pages. Also verify that
    // a user with access to only some Locale module administration pages only
    // sees links to the pages they have access to.
    $admin_list_pages = array(
      'admin/index',
      'admin/config',
      'admin/config/regional',
    );

    foreach ($admin_list_pages as $page) {
      // For the administrator, verify that there are links to Locale's primary
      // configuration pages, but no links to individual sub-configuration
      // pages.
      $this->drupalLogin($this->admin_user);
      $this->drupalGet($page);
      $this->assertLinkByHref('admin/config');
      $this->assertLinkByHref('admin/config/regional/settings');
      $this->assertLinkByHref('admin/config/regional/date-time');
      $this->assertLinkByHref('admin/config/regional/language');
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
      $this->assertLinkByHref('admin/config/regional/translate');
      // On admin/index only, the administrator should also see a "Configure
      // permissions" link for the Locale module.
      if ($page == 'admin/index') {
        $this->assertLinkByHref("admin/people/permissions#module-locale");
      }

      // For a less privileged user, verify that there are no links to Locale's
      // primary configuration pages, but a link to the translate page exists.
      $this->drupalLogin($this->web_user);
      $this->drupalGet($page);
      $this->assertLinkByHref('admin/config');
      $this->assertNoLinkByHref('admin/config/regional/settings');
      $this->assertNoLinkByHref('admin/config/regional/date-time');
      $this->assertNoLinkByHref('admin/config/regional/language');
      $this->assertNoLinkByHref('admin/config/regional/language/configure/session');
      $this->assertNoLinkByHref('admin/config/regional/language/configure/url');
      $this->assertLinkByHref('admin/config/regional/translate');
      // This user cannot configure permissions, so even on admin/index should
      // not see a "Configure permissions" link for the Locale module.
      if ($page == 'admin/index') {
        $this->assertNoLinkByHref("admin/people/permissions#module-locale");
      }
    }
  }

  /**
   * Test compact mode.
   */
  function testCompactMode() {
    $this->drupalGet('admin/compact/on');
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode turns on.');
    $this->drupalGet('admin/compact/on');
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode remains on after a repeat call.');
    $this->drupalGet('');
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');

    $this->drupalGet('admin/compact/off');
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode turns off.');
    $this->drupalGet('admin/compact/off');
    $this->assertEqual($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'deleted', 'Compact mode remains off after a repeat call.');
    $this->drupalGet('');
    $this->assertTrue($this->cookies['Drupal.visitor.admin_compact_mode']['value'], 'Compact mode persists on new requests.');
  }
}

/**
 * Tests authorize.php and related hooks.
 */
class SystemAuthorizeCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Authorize API',
      'description' => 'Tests the authorize.php script and related API.',
      'group' => 'System',
    );
  }

  function setUp() {
    parent::setUp(array('system_test'));

    variable_set('allow_authorize_operations', TRUE);

    // Create an administrator user.
    $this->admin_user = $this->drupalCreateUser(array('administer software updates'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Helper function to initialize authorize.php and load it via drupalGet().
   *
   * Initializing authorize.php needs to happen in the child Drupal
   * installation, not the parent. So, we visit a menu callback provided by
   * system_test.module which calls system_authorized_init() to initialize the
   * $_SESSION inside the test site, not the framework site. This callback
   * redirects to authorize.php when it's done initializing.
   *
   * @see system_authorized_init().
   */
  function drupalGetAuthorizePHP($page_title = 'system-test-auth') {
    $this->drupalGet('system-test/authorize-init/' . $page_title);
  }

  /**
   * Tests the FileTransfer hooks
   */
  function testFileTransferHooks() {
    $page_title = $this->randomName(16);
    $this->drupalGetAuthorizePHP($page_title);
    $this->assertTitle(strtr('@title | Drupal', array('@title' => $page_title)), 'authorize.php page title is correct.');
    $this->assertNoText('It appears you have reached this page in error.');
    $this->assertText('To continue, provide your server connection details');
    // Make sure we see the new connection method added by system_test.
    $this->assertRaw('System Test FileTransfer');
    // Make sure the settings form callback works.
    $this->assertText('System Test Username');
  }
}

/**
 * Test the handling of requests containing 'index.php'.
 */
class SystemIndexPhpTest extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Index.php handling',
      'description' => "Test the handling of requests containing 'index.php'.",
      'group' => 'System',
    );
  }

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

  /**
   * Test index.php handling.
   */
  function testIndexPhpHandling() {
    $index_php = $GLOBALS['base_url'] . '/index.php';

    $this->drupalGet($index_php, array('external' => TRUE));
    $this->assertResponse(200, 'Make sure index.php returns a valid page.');

    $this->drupalGet($index_php, array('external' => TRUE, 'query' => array('q' => 'user')));
    $this->assertResponse(200, 'Make sure index.php?q=user returns a valid page.');

    $this->drupalGet($index_php .'/user', array('external' => TRUE));
    $this->assertResponse(404, "Make sure index.php/user returns a 'page not found'.");
  }
}

/**
 * Test token replacement in strings.
 */
class TokenScanTest extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Token scanning',
      'description' => 'Scan token-like patterns in a dummy text to check token scanning.',
      'group' => 'System',
    );
  }

  /**
   * Scans dummy text, then tests the output.
   */
  function testTokenScan() {
    // Define text with valid and not valid, fake and existing token-like
    // strings.
    $text = 'First a [valid:simple], but dummy token, and a dummy [valid:token with: spaces].';
    $text .= 'Then a [not valid:token].';
    $text .= 'Last an existing token: [node:author:name].';
    $token_wannabes = token_scan($text);

    $this->assertTrue(isset($token_wannabes['valid']['simple']), 'A simple valid token has been matched.');
    $this->assertTrue(isset($token_wannabes['valid']['token with: spaces']), 'A valid token with space characters in the token name has been matched.');
    $this->assertFalse(isset($token_wannabes['not valid']), 'An invalid token with spaces in the token type has not been matched.');
    $this->assertTrue(isset($token_wannabes['node']), 'An existing valid token has been matched.');
  }
}

/**
 * Test case for drupal_valid_token().
 */
class SystemValidTokenTest extends DrupalUnitTestCase {

  /**
   * Flag to indicate whether PHP error reportings should be asserted.
   *
   * @var bool
   */
  protected $assertErrors = TRUE;

  public static function getInfo() {
    return array(
      'name' => 'Token validation',
      'description' => 'Test the security token validation.',
      'group' => 'System',
    );
  }

  /**
   * Tests invalid invocations of drupal_valid_token() that must return FALSE.
   */
  public function testTokenValidation() {
    // The following checks will throw PHP notices, so we disable error
    // assertions.
    $this->assertErrors = FALSE;
    $this->assertFalse(drupal_valid_token(NULL, new stdClass()), 'Token NULL, value object returns FALSE.');
    $this->assertFalse(drupal_valid_token(0, array()), 'Token 0, value array returns FALSE.');
    $this->assertFalse(drupal_valid_token('', array()), "Token '', value array returns FALSE.");
    $this->assertFalse('' === drupal_get_token(array()), 'Token generation does not return an empty string on invalid parameters.');
    $this->assertErrors = TRUE;

    $this->assertFalse(drupal_valid_token(TRUE, 'foo'), 'Token TRUE, value foo returns FALSE.');
    $this->assertFalse(drupal_valid_token(0, 'foo'), 'Token 0, value foo returns FALSE.');
  }

  /**
   * Overrides DrupalTestCase::errorHandler().
   */
  public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
    if ($this->assertErrors) {
      return parent::errorHandler($severity, $message, $file, $line);
    }
    return TRUE;
  }
}