taxonomy.test 76.8 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
<?php

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

/**
 * Provides common helper methods for Taxonomy module tests.
 */
class TaxonomyWebTestCase extends DrupalWebTestCase {

  /**
   * Returns a new vocabulary with random properties.
   */
  function createVocabulary() {
    // Create a vocabulary.
    $vocabulary = new stdClass();
    $vocabulary->name = $this->randomName();
    $vocabulary->description = $this->randomName();
    $vocabulary->machine_name = drupal_strtolower($this->randomName());
    $vocabulary->help = '';
    $vocabulary->nodes = array('article' => 'article');
    $vocabulary->weight = mt_rand(0, 10);
    taxonomy_vocabulary_save($vocabulary);
    return $vocabulary;
  }

  /**
   * Returns a new term with random properties in vocabulary $vid.
   */
  function createTerm($vocabulary) {
    $term = new stdClass();
    $term->name = $this->randomName();
    $term->description = $this->randomName();
    // Use the first available text format.
    $term->format = db_query_range('SELECT format FROM {filter_format}', 0, 1)->fetchField();
    $term->vid = $vocabulary->vid;
    taxonomy_term_save($term);
    return $term;
  }

}

/**
 * Tests the taxonomy vocabulary interface.
 */
class TaxonomyVocabularyFunctionalTest extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy vocabulary interface',
      'description' => 'Test the taxonomy vocabulary interface.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp();
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
    $this->drupalLogin($this->admin_user);
    $this->vocabulary = $this->createVocabulary();
  }

  /**
   * Create, edit and delete a vocabulary via the user interface.
   */
  function testVocabularyInterface() {
    // Visit the main taxonomy administration page.
    $this->drupalGet('admin/structure/taxonomy');

    // Create a new vocabulary.
    $this->clickLink(t('Add vocabulary'));
    $edit = array();
    $machine_name = drupal_strtolower($this->randomName());
    $edit['name'] = $this->randomName();
    $edit['description'] = $this->randomName();
    $edit['machine_name'] = $machine_name;
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->assertRaw(t('Created new vocabulary %name.', array('%name' => $edit['name'])), 'Vocabulary created successfully.');

    // Edit the vocabulary.
    $this->drupalGet('admin/structure/taxonomy');
    $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');
    $this->clickLink(t('edit vocabulary'));
    $edit = array();
    $edit['name'] = $this->randomName();
    $this->drupalPost(NULL, $edit, t('Save'));
    $this->drupalGet('admin/structure/taxonomy');
    $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');

    // Try to submit a vocabulary with a duplicate machine name.
    $edit['machine_name'] = $machine_name;
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
    $this->assertText(t('The machine-readable name is already in use. It must be unique.'));

    // Try to submit an invalid machine name.
    $edit['machine_name'] = '!&^%';
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
    $this->assertText(t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));

    // Ensure that vocabulary titles are escaped properly.
    $edit = array();
    $edit['name'] = 'Don\'t Panic';
    $edit['description'] = $this->randomName();
    $edit['machine_name'] = 'don_t_panic';
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));

    $site_name = variable_get('site_name', 'Drupal');
    $this->drupalGet('admin/structure/taxonomy/don_t_panic');
    $this->assertTitle(t('Don\'t Panic | @site-name', array('@site-name' => $site_name)));
    $this->assertNoTitle(t('Don&#039;t Panic | @site-name', array('@site-name' => $site_name)));
  }

  /**
   * Changing weights on the vocabulary overview with two or more vocabularies.
   */
  function testTaxonomyAdminChangingWeights() {
    // Create some vocabularies.
    for ($i = 0; $i < 10; $i++) {
      $this->createVocabulary();
    }
    // Get all vocabularies and change their weights.
    $vocabularies = taxonomy_get_vocabularies();
    $edit = array();
    foreach ($vocabularies as $key => $vocabulary) {
      $vocabulary->weight = -$vocabulary->weight;
      $vocabularies[$key]->weight = $vocabulary->weight;
      $edit[$key . '[weight]'] = $vocabulary->weight;
    }
    // Saving the new weights via the interface.
    $this->drupalPost('admin/structure/taxonomy', $edit, t('Save'));

    // Load the vocabularies from the database.
    $new_vocabularies = taxonomy_get_vocabularies();

    // Check that the weights are saved in the database correctly.
    foreach ($vocabularies as $key => $vocabulary) {
      $this->assertEqual($new_vocabularies[$key]->weight, $vocabularies[$key]->weight, 'The vocabulary weight was changed.');
    }
  }

  /**
   * Test the vocabulary overview with no vocabularies.
   */
  function testTaxonomyAdminNoVocabularies() {
    // Delete all vocabularies.
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $key => $vocabulary) {
      taxonomy_vocabulary_delete($key);
    }
    // Confirm that no vocabularies are found in the database.
    $this->assertFalse(taxonomy_get_vocabularies(), 'No vocabularies found in the database.');
    $this->drupalGet('admin/structure/taxonomy');
    // Check the default message for no vocabularies.
    $this->assertText(t('No vocabularies available.'), 'No vocabularies were found.');
  }

  /**
   * Deleting a vocabulary.
   */
  function testTaxonomyAdminDeletingVocabulary() {
    // Create a vocabulary.
    $edit = array(
      'name' => $this->randomName(),
      'machine_name' => drupal_strtolower($this->randomName()),
    );
    $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
    $this->assertText(t('Created new vocabulary'), 'New vocabulary was created.');

    // Check the created vocabulary.
    $vocabularies = taxonomy_get_vocabularies();
    $vocabularies_keys = array_keys($vocabularies);
    $vid = $vocabularies[end($vocabularies_keys)]->vid;
    entity_get_controller('taxonomy_vocabulary')->resetCache();
    $vocabulary = taxonomy_vocabulary_load($vid);
    $this->assertTrue($vocabulary, 'Vocabulary found in database.');

    // Delete the vocabulary.
    $edit = array();
    $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/edit', $edit, t('Delete'));
    $this->assertRaw(t('Are you sure you want to delete the vocabulary %name?', array('%name' => $vocabulary->name)), '[confirm deletion] Asks for confirmation.');
    $this->assertText(t('Deleting a vocabulary will delete all the terms in it. This action cannot be undone.'), '[confirm deletion] Inform that all terms will be deleted.');

    // Confirm deletion.
    $this->drupalPost(NULL, NULL, t('Delete'));
    $this->assertRaw(t('Deleted vocabulary %name.', array('%name' => $vocabulary->name)), 'Vocabulary deleted.');
    entity_get_controller('taxonomy_vocabulary')->resetCache();
    $this->assertFalse(taxonomy_vocabulary_load($vid), 'Vocabulary is not found in the database.');
  }

}

/**
 * Tests for taxonomy vocabulary functions.
 */
class TaxonomyVocabularyTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy vocabularies',
      'description' => 'Test loading, saving and deleting vocabularies.',
      'group' => 'Taxonomy',
    );
  }

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

  /**
   * Ensure that when an invalid vocabulary vid is loaded, it is possible
   * to load the same vid successfully if it subsequently becomes valid.
   */
  function testTaxonomyVocabularyLoadReturnFalse() {
    // Load a vocabulary that doesn't exist.
    $vocabularies = taxonomy_get_vocabularies();
    $vid = count($vocabularies) + 1;
    $vocabulary = taxonomy_vocabulary_load($vid);
    // This should not return an object because no such vocabulary exists.
    $this->assertTrue(empty($vocabulary), 'No object loaded.');

    // Create a new vocabulary.
    $this->createVocabulary();
    // Load the vocabulary with the same $vid from earlier.
    // This should return a vocabulary object since it now matches a real vid.
    $vocabulary = taxonomy_vocabulary_load($vid);
    $this->assertTrue(!empty($vocabulary) && is_object($vocabulary), 'Vocabulary is an object.');
    $this->assertEqual($vocabulary->vid, $vid, 'Valid vocabulary vid is the same as our previously invalid one.');
  }

  /**
   * Test deleting a taxonomy that contains terms.
   */
  function testTaxonomyVocabularyDeleteWithTerms() {
    // Delete any existing vocabularies.
    foreach (taxonomy_get_vocabularies() as $vocabulary) {
      taxonomy_vocabulary_delete($vocabulary->vid);
    }

    // Assert that there are no terms left.
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());

    // Create a new vocabulary and add a few terms to it.
    $vocabulary = $this->createVocabulary();
    $terms = array();
    for ($i = 0; $i < 5; $i++) {
      $terms[$i] = $this->createTerm($vocabulary);
    }

    // Set up hierarchy. term 2 is a child of 1 and 4 a child of 1 and 2.
    $terms[2]->parent = array($terms[1]->tid);
    taxonomy_term_save($terms[2]);
    $terms[4]->parent = array($terms[1]->tid, $terms[2]->tid);
    taxonomy_term_save($terms[4]);

    // Assert that there are now 5 terms.
    $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());

    taxonomy_vocabulary_delete($vocabulary->vid);

    // Assert that there are no terms left.
    $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
  }

  /**
   * Ensure that the vocabulary static reset works correctly.
   */
  function testTaxonomyVocabularyLoadStaticReset() {
    $original_vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
    $this->assertTrue(is_object($original_vocabulary), 'Vocabulary loaded successfully.');
    $this->assertEqual($this->vocabulary->name, $original_vocabulary->name, 'Vocabulary loaded successfully.');

    // Change the name and description.
    $vocabulary = $original_vocabulary;
    $vocabulary->name = $this->randomName();
    $vocabulary->description = $this->randomName();
    taxonomy_vocabulary_save($vocabulary);

    // Load the vocabulary.
    $new_vocabulary = taxonomy_vocabulary_load($original_vocabulary->vid);
    $this->assertEqual($new_vocabulary->name, $vocabulary->name);
    $this->assertEqual($new_vocabulary->name, $vocabulary->name);

    // Delete the vocabulary.
    taxonomy_vocabulary_delete($this->vocabulary->vid);
    $vocabularies = taxonomy_get_vocabularies();
    $this->assertTrue(!isset($vocabularies[$this->vocabulary->vid]), 'The vocabulary was deleted.');
  }

  /**
   * Tests for loading multiple vocabularies.
   */
  function testTaxonomyVocabularyLoadMultiple() {

    // Delete any existing vocabularies.
    foreach (taxonomy_get_vocabularies() as $vocabulary) {
      taxonomy_vocabulary_delete($vocabulary->vid);
    }

    // Create some vocabularies and assign weights.
    $vocabulary1 = $this->createVocabulary();
    $vocabulary1->weight = 0;
    taxonomy_vocabulary_save($vocabulary1);
    $vocabulary2 = $this->createVocabulary();
    $vocabulary2->weight = 1;
    taxonomy_vocabulary_save($vocabulary2);
    $vocabulary3 = $this->createVocabulary();
    $vocabulary3->weight = 2;
    taxonomy_vocabulary_save($vocabulary3);

    // Fetch the names for all vocabularies, confirm that they are keyed by
    // machine name.
    $names = taxonomy_vocabulary_get_names();
    $this->assertEqual($names[$vocabulary1->machine_name]->name, $vocabulary1->name, 'Vocabulary 1 name found.');

    // Fetch all of the vocabularies using taxonomy_get_vocabularies().
    // Confirm that the vocabularies are ordered by weight.
    $vocabularies = taxonomy_get_vocabularies();
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary was found in the vocabularies array.');
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary was found in the vocabularies array.');
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary was found in the vocabularies array.');

    // Fetch the vocabularies with taxonomy_vocabulary_load_multiple(), specifying IDs.
    // Ensure they are returned in the same order as the original array.
    $vocabularies = taxonomy_vocabulary_load_multiple(array($vocabulary3->vid, $vocabulary2->vid, $vocabulary1->vid));
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary loaded successfully by ID.');
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary loaded successfully by ID.');
    $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by ID.');

    // Fetch vocabulary 1 by name.
    $vocabulary = current(taxonomy_vocabulary_load_multiple(array(), array('name' => $vocabulary1->name)));
    $this->assertEqual($vocabulary->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name.');

    // Fetch vocabulary 1 by name and ID.
    $this->assertEqual(current(taxonomy_vocabulary_load_multiple(array($vocabulary1->vid), array('name' => $vocabulary1->name)))->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name and ID.');
  }

  /**
   * Tests that machine name changes are properly reflected.
   */
  function testTaxonomyVocabularyChangeMachineName() {
    // Add a field instance to the vocabulary.
    $field = array(
      'field_name' => 'field_test',
      'type' => 'test_field',
    );
    field_create_field($field);
    $instance = array(
      'field_name' => 'field_test',
      'entity_type' => 'taxonomy_term',
      'bundle' => $this->vocabulary->machine_name,
    );
    field_create_instance($instance);

    // Change the machine name.
    $new_name = drupal_strtolower($this->randomName());
    $this->vocabulary->machine_name = $new_name;
    taxonomy_vocabulary_save($this->vocabulary);

    // Check that the field instance is still attached to the vocabulary.
    $this->assertTrue(field_info_instance('taxonomy_term', 'field_test', $new_name), 'The bundle name was updated correctly.');
  }

  /**
   * Test uninstall and reinstall of the taxonomy module.
   */
  function testUninstallReinstall() {
    // Fields and field instances attached to taxonomy term bundles should be
    // removed when the module is uninstalled.
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
    $this->field = array('field_name' => $this->field_name, 'type' => 'text', 'cardinality' => 4);
    $this->field = field_create_field($this->field);
    $this->instance = array(
      'field_name' => $this->field_name,
      'entity_type' => 'taxonomy_term',
      'bundle' => $this->vocabulary->machine_name,
      'label' => $this->randomName() . '_label',
    );
    field_create_instance($this->instance);

    module_disable(array('taxonomy'));
    require_once DRUPAL_ROOT . '/includes/install.inc';
    drupal_uninstall_modules(array('taxonomy'));
    module_enable(array('taxonomy'));

    // Now create a vocabulary with the same name. All field instances
    // connected to this vocabulary name should have been removed when the
    // module was uninstalled. Creating a new field with the same name and
    // an instance of this field on the same bundle name should be successful.
    unset($this->vocabulary->vid);
    taxonomy_vocabulary_save($this->vocabulary);
    unset($this->field['id']);
    field_create_field($this->field);
    field_create_instance($this->instance);
  }

}

/**
 * Unit tests for taxonomy term functions.
 */
class TaxonomyTermFunctionTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term unit tests',
      'description' => 'Unit tests for taxonomy term functions.',
      'group' => 'Taxonomy',
    );
  }

  function testTermDelete() {
    $vocabulary = $this->createVocabulary();
    $valid_term = $this->createTerm($vocabulary);
    // Delete a valid term.
    taxonomy_term_delete($valid_term->tid);
    $terms = taxonomy_term_load_multiple(array(), array('vid' => $vocabulary->vid));
    $this->assertTrue(empty($terms), 'Vocabulary is empty after deletion.');

    // Delete an invalid term. Should not throw any notices.
    taxonomy_term_delete(42);
  }

  /**
   * Test a taxonomy with terms that have multiple parents of different depths.
   */
  function testTaxonomyVocabularyTree() {
    // Create a new vocabulary with 6 terms.
    $vocabulary = $this->createVocabulary();
    $term = array();
    for ($i = 0; $i < 6; $i++) {
      $term[$i] = $this->createTerm($vocabulary);
    }

    // $term[2] is a child of 1 and 5.
    $term[2]->parent = array($term[1]->tid, $term[5]->tid);
    taxonomy_term_save($term[2]);
    // $term[3] is a child of 2.
    $term[3]->parent = array($term[2]->tid);
    taxonomy_term_save($term[3]);
    // $term[5] is a child of 4.
    $term[5]->parent = array($term[4]->tid);
    taxonomy_term_save($term[5]);

    /**
     * Expected tree:
     * term[0] | depth: 0
     * term[1] | depth: 0
     * -- term[2] | depth: 1
     * ---- term[3] | depth: 2
     * term[4] | depth: 0
     * -- term[5] | depth: 1
     * ---- term[2] | depth: 2
     * ------ term[3] | depth: 3
     */
    // Count $term[1] parents with $max_depth = 1.
    $tree = taxonomy_get_tree($vocabulary->vid, $term[1]->tid, 1);
    $this->assertEqual(1, count($tree), 'We have one parent with depth 1.');

    // Count all vocabulary tree elements.
    $tree = taxonomy_get_tree($vocabulary->vid);
    $this->assertEqual(8, count($tree), 'We have all vocabulary tree elements.');

    // Count elements in every tree depth.
    foreach ($tree as $element) {
      if (!isset($depth_count[$element->depth])) {
        $depth_count[$element->depth] = 0;
      }
      $depth_count[$element->depth]++;
    }
    $this->assertEqual(3, $depth_count[0], 'Three elements in taxonomy tree depth 0.');
    $this->assertEqual(2, $depth_count[1], 'Two elements in taxonomy tree depth 1.');
    $this->assertEqual(2, $depth_count[2], 'Two elements in taxonomy tree depth 2.');
    $this->assertEqual(1, $depth_count[3], 'One element in taxonomy tree depth 3.');
  }

}

/**
 * Test for legacy node bug.
 */
class TaxonomyLegacyTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Test for legacy node bug.',
      'description' => 'Posts an article with a taxonomy term and a date prior to 1970.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp('taxonomy');
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'administer nodes', 'bypass node access'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Test taxonomy functionality with nodes prior to 1970.
   */
  function testTaxonomyLegacyNode() {
    // Posts an article with a taxonomy term and a date prior to 1970.
    $langcode = LANGUAGE_NONE;
    $edit = array();
    $edit['title'] = $this->randomName();
    $edit['date'] = '1969-01-01 00:00:00 -0500';
    $edit["body[$langcode][0][value]"] = $this->randomName();
    $edit["field_tags[$langcode]"] = $this->randomName();
    $this->drupalPost('node/add/article', $edit, t('Save'));
    // Checks that the node has been saved.
    $node = $this->drupalGetNodeByTitle($edit['title']);
    $this->assertEqual($node->created, strtotime($edit['date']), 'Legacy node was saved with the right date.');
  }

}

/**
 * Tests for taxonomy term functions.
 */
class TaxonomyTermTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term functions and forms.',
      'description' => 'Test load, save and delete for taxonomy terms.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp('taxonomy');
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
    $this->drupalLogin($this->admin_user);
    $this->vocabulary = $this->createVocabulary();

    $field = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($field);

    $this->instance = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);
  }

  /**
   * Test terms in a single and multiple hierarchy.
   */
  function testTaxonomyTermHierarchy() {
    // Create two taxonomy terms.
    $term1 = $this->createTerm($this->vocabulary);
    $term2 = $this->createTerm($this->vocabulary);

    // Check that hierarchy is flat.
    $vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
    $this->assertEqual(0, $vocabulary->hierarchy, 'Vocabulary is flat.');

    // Edit $term2, setting $term1 as parent.
    $edit = array();
    $edit['parent[]'] = array($term1->tid);
    $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));

    // Check the hierarchy.
    $children = taxonomy_get_children($term1->tid);
    $parents = taxonomy_get_parents($term2->tid);
    $this->assertTrue(isset($children[$term2->tid]), 'Child found correctly.');
    $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');

    // Load and save a term, confirming that parents are still set.
    $term = taxonomy_term_load($term2->tid);
    taxonomy_term_save($term);
    $parents = taxonomy_get_parents($term2->tid);
    $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');

    // Create a third term and save this as a parent of term2.
    $term3 = $this->createTerm($this->vocabulary);
    $term2->parent = array($term1->tid, $term3->tid);
    taxonomy_term_save($term2);
    $parents = taxonomy_get_parents($term2->tid);
    $this->assertTrue(isset($parents[$term1->tid]) && isset($parents[$term3->tid]), 'Both parents found successfully.');
  }

  /**
   * Test that hook_node_$op implementations work correctly.
   *
   * Save & edit a node and assert that taxonomy terms are saved/loaded properly.
   */
  function testTaxonomyNode() {
    // Create two taxonomy terms.
    $term1 = $this->createTerm($this->vocabulary);
    $term2 = $this->createTerm($this->vocabulary);

    // Post an article.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName();
    $edit["body[$langcode][0][value]"] = $this->randomName();
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
    $this->drupalPost('node/add/article', $edit, t('Save'));

    // Check that the term is displayed when the node is viewed.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $this->drupalGet('node/' . $node->nid);
    $this->assertText($term1->name, 'Term is displayed when viewing the node.');

    // Edit the node with a different term.
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term2->tid;
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));

    $this->drupalGet('node/' . $node->nid);
    $this->assertText($term2->name, 'Term is displayed when viewing the node.');

    // Preview the node.
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Preview'));
    $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node.');
    $this->drupalPost(NULL, NULL, t('Preview'));
    $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node again.');
  }

  /**
   * Test term creation with a free-tagging vocabulary from the node form.
   */
  function testNodeTermCreationAndDeletion() {
    // Enable tags in the vocabulary.
    $instance = $this->instance;
    $instance['widget'] = array('type' => 'taxonomy_autocomplete');
    $instance['bundle'] = 'page';
    field_create_instance($instance);
    $terms = array(
      'term1' => $this->randomName(),
      'term2' => $this->randomName() . ', ' . $this->randomName(),
      'term3' => $this->randomName(),
    );

    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName();
    $edit["body[$langcode][0][value]"] = $this->randomName();
    // Insert the terms in a comma separated list. Vocabulary 1 is a
    // free-tagging field created by the default profile.
    $edit[$instance['field_name'] . "[$langcode]"] = drupal_implode_tags($terms);

    // Preview and verify the terms appear but are not created.
    $this->drupalPost('node/add/page', $edit, t('Preview'));
    foreach ($terms as $term) {
      $this->assertText($term, 'The term appears on the node preview.');
    }
    $tree = taxonomy_get_tree($this->vocabulary->vid);
    $this->assertTrue(empty($tree), 'The terms are not created on preview.');

    // taxonomy.module does not maintain its static caches.
    drupal_static_reset();

    // Save, creating the terms.
    $this->drupalPost('node/add/page', $edit, t('Save'));
    $this->assertRaw(t('@type %title has been created.', array('@type' => t('Basic page'), '%title' => $edit["title"])), 'The node was created successfully.');
    foreach ($terms as $term) {
      $this->assertText($term, 'The term was saved and appears on the node page.');
    }

    // Get the created terms.
    $term_objects = array();
    foreach ($terms as $key => $term) {
      $term_objects[$key] = taxonomy_get_term_by_name($term);
      $term_objects[$key] = reset($term_objects[$key]);
    }

    // Test editing the node.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
    foreach ($terms as $term) {
      $this->assertText($term, 'The term was retained after edit and still appears on the node page.');
    }

    // Delete term 1.
    $this->drupalPost('taxonomy/term/' . $term_objects['term1']->tid . '/edit', array(), t('Delete'));
    $this->drupalPost(NULL, NULL, t('Delete'));
    $term_names = array($term_objects['term2']->name, $term_objects['term3']->name);

    // Get the node and verify that the terms that should be there still are.
    $this->drupalGet('node/' . $node->nid);
    foreach ($term_names as $term_name) {
      $this->assertText($term_name, format_string('The term %name appears on the node page after one term %deleted was deleted', array('%name' => $term_name, '%deleted' => $term_objects['term1']->name)));
    }
    $this->assertNoText($term_objects['term1']->name, format_string('The deleted term %name does not appear on the node page.', array('%name' => $term_objects['term1']->name)));

    // Test autocomplete on term 2, which contains a comma.
    // The term will be quoted, and the " will be encoded in unicode (\u0022).
    $input = substr($term_objects['term2']->name, 0, 3);
    $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
    $this->assertRaw('{"\u0022' . $term_objects['term2']->name . '\u0022":"' . $term_objects['term2']->name . '"}', format_string('Autocomplete returns term %term_name after typing the first 3 letters.', array('%term_name' => $term_objects['term2']->name)));

    // Test autocomplete on term 3 - it is alphanumeric only, so no extra
    // quoting.
    $input = substr($term_objects['term3']->name, 0, 3);
    $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
    $this->assertRaw('{"' . $term_objects['term3']->name . '":"' . $term_objects['term3']->name . '"}', format_string('Autocomplete returns term %term_name after typing the first 3 letters.', array('%term_name' => $term_objects['term3']->name)));

    // Test taxonomy autocomplete with a nonexistent field.
    $field_name = $this->randomName();
    $tag = $this->randomName();
    $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
    $this->assertFalse(field_info_field($field_name), format_string('Field %field_name does not exist.', array('%field_name' => $field_name)));
    $this->drupalGet('taxonomy/autocomplete/' . $field_name . '/' . $tag);
    $this->assertRaw($message, 'Autocomplete returns correct error message when the taxonomy field does not exist.');

    // Test the autocomplete path without passing a field_name and terms.
    // This should not trigger a PHP notice.
    $field_name = '';
    $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
    $this->drupalGet('taxonomy/autocomplete');
    $this->assertRaw($message, 'Autocomplete returns correct error message when no taxonomy field is given.');
  }

  /**
   * Tests term autocompletion edge cases with slashes in the names.
   */
  function testTermAutocompletion() {
    // Add a term with a slash in the name.
    $first_term = $this->createTerm($this->vocabulary);
    $first_term->name = '10/16/2011';
    taxonomy_term_save($first_term);
    // Add another term that differs after the slash character.
    $second_term = $this->createTerm($this->vocabulary);
    $second_term->name = '10/17/2011';
    taxonomy_term_save($second_term);
    // Add another term that has both a comma and a slash character.
    $third_term = $this->createTerm($this->vocabulary);
    $third_term->name = 'term with, a comma and / a slash';
    taxonomy_term_save($third_term);

    // Try to autocomplete a term name that matches both terms.
    // We should get both term in a json encoded string.
    $input = '10/';
    $path = 'taxonomy/autocomplete/taxonomy_';
    $path .= $this->vocabulary->machine_name . '/' . $input;
    // The result order is not guaranteed, so check each term separately.
    $url = url($path, array('absolute' => TRUE));
    $result = drupal_http_request($url);
    $data = drupal_json_decode($result->data);
    $this->assertEqual($data[$first_term->name], check_plain($first_term->name), 'Autocomplete returned the first matching term.');
    $this->assertEqual($data[$second_term->name], check_plain($second_term->name), 'Autocomplete returned the second matching term.');

    // Try to autocomplete a term name that matches first term.
    // We should only get the first term in a json encoded string.
    $input = '10/16';
    $url = 'taxonomy/autocomplete/taxonomy_';
    $url .= $this->vocabulary->machine_name . '/' . $input;
    $this->drupalGet($url);
    $target = array($first_term->name => check_plain($first_term->name));
    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');

    // Try to autocomplete a term name with both a comma and a slash.
    $input = '"term with, comma and / a';
    $url = 'taxonomy/autocomplete/taxonomy_';
    $url .= $this->vocabulary->machine_name . '/' . $input;
    $this->drupalGet($url);
    $n = $third_term->name;
    // Term names containing commas or quotes must be wrapped in quotes.
    if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
      $n = '"' . str_replace('"', '""', $third_term->name) . '"';
    }
    $target = array($n => check_plain($third_term->name));
    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
  }

  /**
   * Save, edit and delete a term using the user interface.
   */
  function testTermInterface() {
    $edit = array(
      'name' => $this->randomName(12),
      'description[value]' => $this->randomName(100),
    );
    // Explicitly set the parents field to 'root', to ensure that
    // taxonomy_form_term_submit() handles the invalid term ID correctly.
    $edit['parent[]'] = array(0);

    // Create the term to edit.
    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));

    $terms = taxonomy_get_term_by_name($edit['name']);
    $term = reset($terms);
    $this->assertNotNull($term, 'Term found in database.');

    // Submitting a term takes us to the add page; we need the List page.
    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);

    // Test edit link as accessed from Taxonomy administration pages.
    // Because Simpletest creates its own database when running tests, we know
    // the first edit link found on the listing page is to our term.
    $this->clickLink(t('edit'));

    $this->assertRaw($edit['name'], 'The randomly generated term name is present.');
    $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');

    $edit = array(
      'name' => $this->randomName(14),
      'description[value]' => $this->randomName(102),
    );

    // Edit the term.
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));

    // Check that the term is still present at admin UI after edit.
    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
    $this->assertText($edit['name'], 'The randomly generated term name is present.');
    $this->assertLink(t('edit'));

    // View the term and check that it is correct.
    $this->drupalGet('taxonomy/term/' . $term->tid);
    $this->assertText($edit['name'], 'The randomly generated term name is present.');
    $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');

    // Did this page request display a 'term-listing-heading'?
    $this->assertPattern('|class="taxonomy-term-description"|', 'Term page displayed the term description element.');
    // Check that it does NOT show a description when description is blank.
    $term->description = '';
    taxonomy_term_save($term);
    $this->drupalGet('taxonomy/term/' . $term->tid);
    $this->assertNoPattern('|class="taxonomy-term-description"|', 'Term page did not display the term description when description was blank.');

    // Check that the term feed page is working.
    $this->drupalGet('taxonomy/term/' . $term->tid . '/feed');

    // Check that the term edit page does not try to interpret additional path
    // components as arguments for taxonomy_form_term().
    $this->drupalGet('taxonomy/term/' . $term->tid . '/edit/' . $this->randomName());

    // Delete the term.
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', array(), t('Delete'));
    $this->drupalPost(NULL, NULL, t('Delete'));

    // Assert that the term no longer exists.
    $this->drupalGet('taxonomy/term/' . $term->tid);
    $this->assertResponse(404, 'The taxonomy term page was not found.');
  }

  /**
   * Save, edit and delete a term using the user interface.
   */
  function testTermReorder() {
    $this->createTerm($this->vocabulary);
    $this->createTerm($this->vocabulary);
    $this->createTerm($this->vocabulary);

    // Fetch the created terms in the default alphabetical order, i.e. term1
    // precedes term2 alphabetically, and term2 precedes term3.
    drupal_static_reset('taxonomy_get_tree');
    drupal_static_reset('taxonomy_get_treeparent');
    drupal_static_reset('taxonomy_get_treeterms');
    list($term1, $term2, $term3) = taxonomy_get_tree($this->vocabulary->vid);

    $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);

    // Each term has four hidden fields, "tid:1:0[tid]", "tid:1:0[parent]",
    // "tid:1:0[depth]", and "tid:1:0[weight]". Change the order to term2,
    // term3, term1 by setting weight property, make term3 a child of term2 by
    // setting the parent and depth properties, and update all hidden fields.
    $edit = array(
      'tid:' . $term2->tid . ':0[tid]' => $term2->tid,
      'tid:' . $term2->tid . ':0[parent]' => 0,
      'tid:' . $term2->tid . ':0[depth]' => 0,
      'tid:' . $term2->tid . ':0[weight]' => 0,
      'tid:' . $term3->tid . ':0[tid]' => $term3->tid,
      'tid:' . $term3->tid . ':0[parent]' => $term2->tid,
      'tid:' . $term3->tid . ':0[depth]' => 1,
      'tid:' . $term3->tid . ':0[weight]' => 1,
      'tid:' . $term1->tid . ':0[tid]' => $term1->tid,
      'tid:' . $term1->tid . ':0[parent]' => 0,
      'tid:' . $term1->tid . ':0[depth]' => 0,
      'tid:' . $term1->tid . ':0[weight]' => 2,
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    drupal_static_reset('taxonomy_get_tree');
    drupal_static_reset('taxonomy_get_treeparent');
    drupal_static_reset('taxonomy_get_treeterms');
    $terms = taxonomy_get_tree($this->vocabulary->vid);
    $this->assertEqual($terms[0]->tid, $term2->tid, 'Term 2 was moved above term 1.');
    $this->assertEqual($terms[1]->parents, array($term2->tid), 'Term 3 was made a child of term 2.');
    $this->assertEqual($terms[2]->tid, $term1->tid, 'Term 1 was moved below term 2.');

    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name, array(), t('Reset to alphabetical'));
    // Submit confirmation form.
    $this->drupalPost(NULL, array(), t('Reset to alphabetical'));

    drupal_static_reset('taxonomy_get_tree');
    drupal_static_reset('taxonomy_get_treeparent');
    drupal_static_reset('taxonomy_get_treeterms');
    $terms = taxonomy_get_tree($this->vocabulary->vid);
    $this->assertEqual($terms[0]->tid, $term1->tid, 'Term 1 was moved to back above term 2.');
    $this->assertEqual($terms[1]->tid, $term2->tid, 'Term 2 was moved to back below term 1.');
    $this->assertEqual($terms[2]->tid, $term3->tid, 'Term 3 is still below term 2.');
    $this->assertEqual($terms[2]->parents, array($term2->tid), 'Term 3 is still a child of term 2.' . var_export($terms[1]->tid, 1));
  }

  /**
   * Test saving a term with multiple parents through the UI.
   */
  function testTermMultipleParentsInterface() {
    // Add a new term to the vocabulary so that we can have multiple parents.
    $parent = $this->createTerm($this->vocabulary);

    // Add a new term with multiple parents.
    $edit = array(
      'name' => $this->randomName(12),
      'description[value]' => $this->randomName(100),
      'parent[]' => array(0, $parent->tid),
    );
    // Save the new term.
    $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));

    // Check that the term was successfully created.
    $terms = taxonomy_get_term_by_name($edit['name']);
    $term = reset($terms);
    $this->assertNotNull($term, 'Term found in database.');
    $this->assertEqual($edit['name'], $term->name, 'Term name was successfully saved.');
    $this->assertEqual($edit['description[value]'], $term->description, 'Term description was successfully saved.');
    // Check that the parent tid is still there. The other parent (<root>) is
    // not added by taxonomy_get_parents().
    $parents = taxonomy_get_parents($term->tid);
    $parent = reset($parents);
    $this->assertEqual($edit['parent[]'][1], $parent->tid, 'Term parents were successfully saved.');
  }

  /**
   * Test taxonomy_get_term_by_name().
   */
  function testTaxonomyGetTermByName() {
    $term = $this->createTerm($this->vocabulary);

    // Load the term with the exact name.
    $terms = taxonomy_get_term_by_name($term->name);
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name.');

    // Load the term with space concatenated.
    $terms  = taxonomy_get_term_by_name('  ' . $term->name . '   ');
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with extra whitespace.');

    // Load the term with name uppercased.
    $terms = taxonomy_get_term_by_name(strtoupper($term->name));
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with uppercased name.');

    // Load the term with name lowercased.
    $terms = taxonomy_get_term_by_name(strtolower($term->name));
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with lowercased name.');

    // Try to load an invalid term name.
    $terms = taxonomy_get_term_by_name('Banana');
    $this->assertFalse($terms);

    // Try to load the term using a substring of the name.
    $terms = taxonomy_get_term_by_name(drupal_substr($term->name, 2));
    $this->assertFalse($terms);

    // Create a new term in a different vocabulary with the same name.
    $new_vocabulary = $this->createVocabulary();
    $new_term = new stdClass();
    $new_term->name = $term->name;
    $new_term->vid = $new_vocabulary->vid;
    taxonomy_term_save($new_term);

    // Load multiple terms with the same name.
    $terms = taxonomy_get_term_by_name($term->name);
    $this->assertEqual(count($terms), 2, 'Two terms loaded with the same name.');

    // Load single term when restricted to one vocabulary.
    $terms = taxonomy_get_term_by_name($term->name, $this->vocabulary->machine_name);
    $this->assertEqual(count($terms), 1, 'One term loaded when restricted by vocabulary.');
    $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name and vocabulary machine name.');

    // Create a new term with another name.
    $term2 = $this->createTerm($this->vocabulary);

    // Try to load a term by name that doesn't exist in this vocabulary but
    // exists in another vocabulary.
    $terms = taxonomy_get_term_by_name($term2->name, $new_vocabulary->machine_name);
    $this->assertFalse($terms, 'Invalid term name restricted by vocabulary machine name not loaded.');

    // Try to load terms filtering by a non-existing vocabulary.
    $terms = taxonomy_get_term_by_name($term2->name, 'non_existing_vocabulary');
    $this->assertEqual(count($terms), 0, 'No terms loaded when restricted by a non-existing vocabulary.');
  }

}

/**
 * Tests the rendering of term reference fields in RSS feeds.
 */
class TaxonomyRSSTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy RSS Content.',
      'description' => 'Ensure that data added as terms appears in RSS feeds if "RSS Category" format is selected.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp('taxonomy');
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access', 'administer content types'));
    $this->drupalLogin($this->admin_user);
    $this->vocabulary = $this->createVocabulary();

    $field = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($field);

    $this->instance = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);
  }

  /**
   * Tests that terms added to nodes are displayed in core RSS feed.
   *
   * Create a node and assert that taxonomy terms appear in rss.xml.
   */
  function testTaxonomyRSS() {
    // Create two taxonomy terms.
    $term1 = $this->createTerm($this->vocabulary);

    // RSS display must be added manually.
    $this->drupalGet("admin/structure/types/manage/article/display");
    $edit = array(
      "view_modes_custom[rss]" => '1',
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    // Change the format to 'RSS category'.
    $this->drupalGet("admin/structure/types/manage/article/display/rss");
    $edit = array(
      "fields[taxonomy_" . $this->vocabulary->machine_name . "][type]" => 'taxonomy_term_reference_rss_category',
    );
    $this->drupalPost(NULL, $edit, t('Save'));

    // Post an article.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName();
    $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
    $this->drupalPost('node/add/article', $edit, t('Save'));

    // Check that the term is displayed when the RSS feed is viewed.
    $this->drupalGet('rss.xml');
    $test_element = array(
      'key' => 'category',
      'value' => $term1->name,
      'attributes' => array(
        'domain' => url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE)),
      ),
    );
    $this->assertRaw(format_xml_elements(array($test_element)), 'Term is displayed when viewing the rss feed.');
  }

}

/**
 * Tests the hook implementations that maintain the taxonomy index.
 */
class TaxonomyTermIndexTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term index',
      'description' => 'Tests the hook implementations that maintain the taxonomy index.',
      'group' => 'Taxonomy',
    );
  }

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

    // Create an administrative user.
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
    $this->drupalLogin($this->admin_user);

    // Create a vocabulary and add two term reference fields to article nodes.
    $this->vocabulary = $this->createVocabulary();

    $this->field_name_1 = drupal_strtolower($this->randomName());
    $this->field_1 = array(
      'field_name' => $this->field_name_1,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($this->field_1);
    $this->instance_1 = array(
      'field_name' => $this->field_name_1,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance_1);

    $this->field_name_2 = drupal_strtolower($this->randomName());
    $this->field_2 = array(
      'field_name' => $this->field_name_2,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($this->field_2);
    $this->instance_2 = array(
      'field_name' => $this->field_name_2,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance_2);
  }

  /**
   * Tests that the taxonomy index is maintained properly.
   */
  function testTaxonomyIndex() {
    // Create terms in the vocabulary.
    $term_1 = $this->createTerm($this->vocabulary);
    $term_2 = $this->createTerm($this->vocabulary);

    // Post an article.
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = $this->randomName();
    $edit["body[$langcode][0][value]"] = $this->randomName();
    $edit["{$this->field_name_1}[$langcode][]"] = $term_1->tid;
    $edit["{$this->field_name_2}[$langcode][]"] = $term_1->tid;
    $this->drupalPost('node/add/article', $edit, t('Save'));

    // Check that the term is indexed, and only once.
    $node = $this->drupalGetNodeByTitle($edit["title"]);
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');

    // Update the article to change one term.
    $edit["{$this->field_name_1}[$langcode][]"] = $term_2->tid;
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));

    // Check that both terms are indexed.
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_2->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 2 is indexed.');

    // Update the article to change another term.
    $edit["{$this->field_name_2}[$langcode][]"] = $term_2->tid;
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));

    // Check that only one term is indexed.
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_2->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');

    // Redo the above tests without interface.
    $update_node = array(
      'nid' => $node->nid,
      'vid' => $node->vid,
      'uid' => $node->uid,
      'type' => $node->type,
      'title' => $this->randomName(),
    );

    // Update the article with no term changed.
    $updated_node = (object) $update_node;
    node_save($updated_node);

    // Check that the index was not changed.
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_2->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');

    // Update the article to change one term.
    $update_node[$this->field_name_1][$langcode] = array(array('tid' => $term_1->tid));
    $updated_node = (object) $update_node;
    node_save($updated_node);

    // Check that both terms are indexed.
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_2->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 2 is indexed.');

    // Update the article to change another term.
    $update_node[$this->field_name_2][$langcode] = array(array('tid' => $term_1->tid));
    $updated_node = (object) $update_node;
    node_save($updated_node);

    // Check that only one term is indexed.
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_1->tid,
    ))->fetchField();
    $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
    $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
      ':nid' => $node->nid,
      ':tid' => $term_2->tid,
    ))->fetchField();
    $this->assertEqual(0, $index_count, 'Term 2 is not indexed.');
  }

  /**
   * Tests that there is a link to the parent term on the child term page.
   */
  function testTaxonomyTermHierarchyBreadcrumbs() {
    // Create two taxonomy terms and set term2 as the parent of term1.
    $term1 = $this->createTerm($this->vocabulary);
    $term2 = $this->createTerm($this->vocabulary);
    $term1->parent = array($term2->tid);
    taxonomy_term_save($term1);

    // Verify that the page breadcrumbs include a link to the parent term.
    $this->drupalGet('taxonomy/term/' . $term1->tid);
    $this->assertRaw(l($term2->name, 'taxonomy/term/' . $term2->tid), 'Parent term link is displayed when viewing the node.');
  }

}

/**
 * Test the taxonomy_term_load_multiple() function.
 */
class TaxonomyLoadMultipleTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term multiple loading',
      'description' => 'Test the loading of multiple taxonomy terms at once',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp();
    $this->taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
    $this->drupalLogin($this->taxonomy_admin);
  }

  /**
   * Create a vocabulary and some taxonomy terms, ensuring they're loaded
   * correctly using taxonomy_term_load_multiple().
   */
  function testTaxonomyTermMultipleLoad() {
    // Create a vocabulary.
    $vocabulary = $this->createVocabulary();

    // Create five terms in the vocabulary.
    $i = 0;
    while ($i < 5) {
      $i++;
      $this->createTerm($vocabulary);
    }
    // Load the terms from the vocabulary.
    $terms = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
    $count = count($terms);
    $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. !count terms.', array('!count' => $count)));

    // Load the same terms again by tid.
    $terms2 = taxonomy_term_load_multiple(array_keys($terms));
    $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.');
    $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.');

    // Load the terms by tid, with a condition on vid.
    $terms3 = taxonomy_term_load_multiple(array_keys($terms2), array('vid' => $vocabulary->vid));
    $this->assertEqual($terms2, $terms3);

    // Remove one term from the array, then delete it.
    $deleted = array_shift($terms3);
    taxonomy_term_delete($deleted->tid);
    $deleted_term = taxonomy_term_load($deleted->tid);
    $this->assertFalse($deleted_term);

    // Load terms from the vocabulary by vid.
    $terms4 = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
    $this->assertEqual(count($terms4), 4, 'Correct number of terms were loaded.');
    $this->assertFalse(isset($terms4[$deleted->tid]));

    // Create a single term and load it by name.
    $term = $this->createTerm($vocabulary);
    $loaded_terms = taxonomy_term_load_multiple(array(), array('name' => $term->name));
    $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.');
    $loaded_term = reset($loaded_terms);
    $this->assertEqual($term->tid, $loaded_term->tid, 'Term loaded by name successfully.');
  }
}

/**
 * Tests for taxonomy hook invocation.
 */
class TaxonomyHooksTestCase extends TaxonomyWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term hooks',
      'description' => 'Hooks for taxonomy term load/save/delete.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp('taxonomy', 'taxonomy_test');
    module_load_include('inc', 'taxonomy', 'taxonomy.pages');
    $taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
    $this->drupalLogin($taxonomy_admin);
  }

  /**
   * Test that hooks are run correctly on creating, editing, viewing,
   * and deleting a term.
   *
   * @see taxonomy_test.module
   */
  function testTaxonomyTermHooks() {
    $vocabulary = $this->createVocabulary();

    // Create a term with one antonym.
    $edit = array(
      'name' => $this->randomName(),
      'antonym' => 'Long',
    );
    $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add', $edit, t('Save'));
    $terms = taxonomy_get_term_by_name($edit['name']);
    $term = reset($terms);
    $this->assertEqual($term->antonym, $edit['antonym'], 'Antonym was loaded into the term object.');

    // Update the term with a different antonym.
    $edit = array(
      'name' => $this->randomName(),
      'antonym' => 'Short',
    );
    $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
    taxonomy_terms_static_reset();
    $term = taxonomy_term_load($term->tid);
    $this->assertEqual($edit['antonym'], $term->antonym, 'Antonym was successfully edited.');

    // View the term and ensure that hook_taxonomy_term_view() and
    // hook_entity_view() are invoked.
    $term = taxonomy_term_load($term->tid);
    $term_build = taxonomy_term_page($term);
    $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_term_view_check']), 'hook_taxonomy_term_view() was invoked when viewing the term.');
    $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_entity_view_check']), 'hook_entity_view() was invoked when viewing the term.');

    // Delete the term.
    taxonomy_term_delete($term->tid);
    $antonym = db_query('SELECT tid FROM {taxonomy_term_antonym} WHERE tid = :tid', array(':tid' => $term->tid))->fetchField();
    $this->assertFalse($antonym, 'The antonym were deleted from the database.');
  }

}

/**
 * Tests for taxonomy term field and formatter.
 */
class TaxonomyTermFieldTestCase extends TaxonomyWebTestCase {

  protected $instance;
  protected $vocabulary;

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy term reference field',
      'description' => 'Test the creation of term fields.',
      'group' => 'Taxonomy',
    );
  }

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

    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
    $this->drupalLogin($web_user);
    $this->vocabulary = $this->createVocabulary();

    // Setup a field and instance.
    $this->field_name = drupal_strtolower($this->randomName());
    $this->field = array(
      'field_name' => $this->field_name,
      'type' => 'taxonomy_term_reference',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => '0',
          ),
        ),
      )
    );
    field_create_field($this->field);
    $this->instance = array(
      'field_name' => $this->field_name,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'full' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);
  }

  /**
   * Test term field validation.
   */
  function testTaxonomyTermFieldValidation() {
    // Test valid and invalid values with field_attach_validate().
    $langcode = LANGUAGE_NONE;
    $entity = field_test_create_stub_entity();
    $term = $this->createTerm($this->vocabulary);
    $entity->{$this->field_name}[$langcode][0]['tid'] = $term->tid;
    try {
      field_attach_validate('test_entity', $entity);
      $this->pass('Correct term does not cause validation error.');
    }
    catch (FieldValidationException $e) {
      $this->fail('Correct term does not cause validation error.');
    }

    $entity = field_test_create_stub_entity();
    $bad_term = $this->createTerm($this->createVocabulary());
    $entity->{$this->field_name}[$langcode][0]['tid'] = $bad_term->tid;
    try {
      field_attach_validate('test_entity', $entity);
      $this->fail('Wrong term causes validation error.');
    }
    catch (FieldValidationException $e) {
      $this->pass('Wrong term causes validation error.');
    }
  }

  /**
   * Test widgets.
   */
  function testTaxonomyTermFieldWidgets() {
    // Create a term in the vocabulary.
    $term = $this->createTerm($this->vocabulary);

    // Display creation form.
    $langcode = LANGUAGE_NONE;
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');

    // Submit with some value.
    $edit = array(
      "{$this->field_name}[$langcode]" => array($term->tid),
    );
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');

    // Display the object.
    $entity = field_test_entity_test_load($id);
    $entities = array($id => $entity);
    field_attach_prepare_view('test_entity', $entities, 'full');
    $entity->content = field_attach_view('test_entity', $entity, 'full');
    $this->content = drupal_render($entity->content);
    $this->assertText($term->name, 'Term name is displayed.');

    // Delete the vocabulary and verify that the widget is gone.
    taxonomy_vocabulary_delete($this->vocabulary->vid);
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertNoFieldByName("{$this->field_name}[$langcode]", '', 'Widget is not displayed.');
  }

  /**
   * Tests that vocabulary machine name changes are mirrored in field definitions.
   */
  function testTaxonomyTermFieldChangeMachineName() {
    // Add several entries in the 'allowed_values' setting, to make sure that
    // they all get updated.
    $this->field['settings']['allowed_values'] = array(
      array(
        'vocabulary' => $this->vocabulary->machine_name,
        'parent' => '0',
      ),
      array(
        'vocabulary' => $this->vocabulary->machine_name,
        'parent' => '0',
      ),
      array(
        'vocabulary' => 'foo',
        'parent' => '0',
      ),
    );
    field_update_field($this->field);
    // Change the machine name.
    $old_name = $this->vocabulary->machine_name;
    $new_name = drupal_strtolower($this->randomName());
    $this->vocabulary->machine_name = $new_name;
    taxonomy_vocabulary_save($this->vocabulary);

    // Check that entity bundles are properly updated.
    $info = entity_get_info('taxonomy_term');
    $this->assertFalse(isset($info['bundles'][$old_name]), 'The old bundle name does not appear in entity_get_info().');
    $this->assertTrue(isset($info['bundles'][$new_name]), 'The new bundle name appears in entity_get_info().');

    // Check that the field instance is still attached to the vocabulary.
    $field = field_info_field($this->field_name);
    $allowed_values = $field['settings']['allowed_values'];
    $this->assertEqual($allowed_values[0]['vocabulary'], $new_name, 'Index 0: Machine name was updated correctly.');
    $this->assertEqual($allowed_values[1]['vocabulary'], $new_name, 'Index 1: Machine name was updated correctly.');
    $this->assertEqual($allowed_values[2]['vocabulary'], 'foo', 'Index 2: Machine name was left untouched.');
  }

}

/**
 * Tests a taxonomy term reference field that allows multiple vocabularies.
 */
class TaxonomyTermFieldMultipleVocabularyTestCase extends TaxonomyWebTestCase {

  protected $instance;
  protected $vocabulary1;
  protected $vocabulary2;

  public static function getInfo() {
    return array(
      'name' => 'Multiple vocabulary term reference field',
      'description' => 'Tests term reference fields that allow multiple vocabularies.',
      'group' => 'Taxonomy',
    );
  }

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

    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
    $this->drupalLogin($web_user);
    $this->vocabulary1 = $this->createVocabulary();
    $this->vocabulary2 = $this->createVocabulary();

    // Set up a field and instance.
    $this->field_name = drupal_strtolower($this->randomName());
    $this->field = array(
      'field_name' => $this->field_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary1->machine_name,
            'parent' => '0',
          ),
          array(
            'vocabulary' => $this->vocabulary2->machine_name,
            'parent' => '0',
          ),
        ),
      )
    );
    field_create_field($this->field);
    $this->instance = array(
      'field_name' => $this->field_name,
      'entity_type' => 'test_entity',
      'bundle' => 'test_bundle',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'full' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);
  }

  /**
   * Tests term reference field and widget with multiple vocabularies.
   */
  function testTaxonomyTermFieldMultipleVocabularies() {
    // Create a term in each vocabulary.
    $term1 = $this->createTerm($this->vocabulary1);
    $term2 = $this->createTerm($this->vocabulary2);

    // Submit an entity with both terms.
    $langcode = LANGUAGE_NONE;
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is displayed.');
    $edit = array(
      "{$this->field_name}[$langcode][]" => array($term1->tid, $term2->tid),
    );
    $this->drupalPost(NULL, $edit, t('Save'));
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
    $id = $match[1];
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');

    // Render the entity.
    $entity = field_test_entity_test_load($id);
    $entities = array($id => $entity);
    field_attach_prepare_view('test_entity', $entities, 'full');
    $entity->content = field_attach_view('test_entity', $entity, 'full');
    $this->content = drupal_render($entity->content);
    $this->assertText($term1->name, 'Term 1 name is displayed.');
    $this->assertText($term2->name, 'Term 2 name is displayed.');

    // Delete vocabulary 2.
    taxonomy_vocabulary_delete($this->vocabulary2->vid);

    // Re-render the content.
    $entity = field_test_entity_test_load($id);
    $entities = array($id => $entity);
    field_attach_prepare_view('test_entity', $entities, 'full');
    $entity->content = field_attach_view('test_entity', $entity, 'full');
    $this->plainTextContent = FALSE;
    $this->content = drupal_render($entity->content);

    // Term 1 should still be displayed; term 2 should not be.
    $this->assertText($term1->name, 'Term 1 name is displayed.');
    $this->assertNoText($term2->name, 'Term 2 name is not displayed.');

    // Verify that field and instance settings are correct.
    $field_info = field_info_field($this->field_name);
    $this->assertEqual(sizeof($field_info['settings']['allowed_values']), 1, 'Only one vocabulary is allowed for the field.');

    // The widget should still be displayed.
    $this->drupalGet('test-entity/add/test-bundle');
    $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is still displayed.');

    // Term 1 should still pass validation.
    $edit = array(
      "{$this->field_name}[$langcode][]" => array($term1->tid),
    );
    $this->drupalPost(NULL, $edit, t('Save'));
  }

}

/**
 * Test taxonomy token replacement in strings.
 */
class TaxonomyTokenReplaceTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy token replacement',
      'description' => 'Generates text using placeholders for dummy content to check taxonomy token replacement.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp();
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
    $this->drupalLogin($this->admin_user);
    $this->vocabulary = $this->createVocabulary();
    $this->langcode = LANGUAGE_NONE;

    $field = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'type' => 'taxonomy_term_reference',
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => $this->vocabulary->machine_name,
            'parent' => 0,
          ),
        ),
      ),
    );
    field_create_field($field);

    $this->instance = array(
      'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
      'bundle' => 'article',
      'entity_type' => 'node',
      'widget' => array(
        'type' => 'options_select',
      ),
      'display' => array(
        'default' => array(
          'type' => 'taxonomy_term_reference_link',
        ),
      ),
    );
    field_create_instance($this->instance);
  }

  /**
   * Creates some terms and a node, then tests the tokens generated from them.
   */
  function testTaxonomyTokenReplacement() {
    global $language;

    // Create two taxonomy terms.
    $term1 = $this->createTerm($this->vocabulary);
    $term2 = $this->createTerm($this->vocabulary);

    // Edit $term2, setting $term1 as parent.
    $edit = array();
    $edit['name'] = '<blink>Blinking Text</blink>';
    $edit['parent[]'] = array($term1->tid);
    $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));

    // Create node with term2.
    $edit = array();
    $node = $this->drupalCreateNode(array('type' => 'article'));
    $edit[$this->instance['field_name'] . '[' . $this->langcode . '][]'] = $term2->tid;
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));

    // Generate and test sanitized tokens for term1.
    $tests = array();
    $tests['[term:tid]'] = $term1->tid;
    $tests['[term:name]'] = check_plain($term1->name);
    $tests['[term:description]'] = check_markup($term1->description, $term1->format);
    $tests['[term:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
    $tests['[term:node-count]'] = 0;
    $tests['[term:parent:name]'] = '[term:parent:name]';
    $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);

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

    // Generate and test sanitized tokens for term2.
    $tests = array();
    $tests['[term:tid]'] = $term2->tid;
    $tests['[term:name]'] = check_plain($term2->name);
    $tests['[term:description]'] = check_markup($term2->description, $term2->format);
    $tests['[term:url]'] = url('taxonomy/term/' . $term2->tid, array('absolute' => TRUE));
    $tests['[term:node-count]'] = 1;
    $tests['[term:parent:name]'] = check_plain($term1->name);
    $tests['[term:parent:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
    $tests['[term:parent:parent:name]'] = '[term:parent:parent:name]';
    $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);

    // 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('term' => $term2), array('language' => $language));
      $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
    }

    // Generate and test unsanitized tokens.
    $tests['[term:name]'] = $term2->name;
    $tests['[term:description]'] = $term2->description;
    $tests['[term:parent:name]'] = $term1->name;
    $tests['[term:vocabulary:name]'] = $this->vocabulary->name;

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

    // Generate and test sanitized tokens.
    $tests = array();
    $tests['[vocabulary:vid]'] = $this->vocabulary->vid;
    $tests['[vocabulary:name]'] = check_plain($this->vocabulary->name);
    $tests['[vocabulary:description]'] = filter_xss($this->vocabulary->description);
    $tests['[vocabulary:node-count]'] = 1;
    $tests['[vocabulary:term-count]'] = 2;

    // 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('vocabulary' => $this->vocabulary), array('language' => $language));
      $this->assertEqual($output, $expected, format_string('Sanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
    }

    // Generate and test unsanitized tokens.
    $tests['[vocabulary:name]'] = $this->vocabulary->name;
    $tests['[vocabulary:description]'] = $this->vocabulary->description;

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

}

/**
 * Tests for verifying that taxonomy pages use the correct theme.
 */
class TaxonomyThemeTestCase extends TaxonomyWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Taxonomy theme switching',
      'description' => 'Verifies that various taxonomy pages use the expected theme.',
      'group' => 'Taxonomy',
    );
  }

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

    // Make sure we are using distinct default and administrative themes for
    // the duration of these tests.
    variable_set('theme_default', 'bartik');
    variable_set('admin_theme', 'seven');

    // Create and log in as a user who has permission to add and edit taxonomy
    // terms and view the administrative theme.
    $admin_user = $this->drupalCreateUser(array('administer taxonomy', 'view the administration theme'));
    $this->drupalLogin($admin_user);
  }

  /**
   * Test the theme used when adding, viewing and editing taxonomy terms.
   */
  function testTaxonomyTermThemes() {
    // Adding a term to a vocabulary is considered an administrative action and
    // should use the administrative theme.
    $vocabulary = $this->createVocabulary();
    $this->drupalGet('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add');
    $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for adding a taxonomy term.");

    // Viewing a taxonomy term should use the default theme.
    $term = $this->createTerm($vocabulary);
    $this->drupalGet('taxonomy/term/' . $term->tid);
    $this->assertRaw('bartik/css/style.css', "The default theme's CSS appears on the page for viewing a taxonomy term.");

    // Editing a taxonomy term should use the same theme as adding one.
    $this->drupalGet('taxonomy/term/' . $term->tid . '/edit');
    $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for editing a taxonomy term.");
  }

}

/**
 * Tests the functionality of EntityFieldQuery for taxonomy entities.
 */
class TaxonomyEFQTestCase extends TaxonomyWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Taxonomy EntityFieldQuery',
      'description' => 'Verifies operation of a taxonomy-based EntityFieldQuery.',
      'group' => 'Taxonomy',
    );
  }

  function setUp() {
    parent::setUp();
    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
    $this->drupalLogin($this->admin_user);
    $this->vocabulary = $this->createVocabulary();
  }

  /**
   * Tests that a basic taxonomy EntityFieldQuery works.
   */
  function testTaxonomyEFQ() {
    $terms = array();
    for ($i = 0; $i < 5; $i++) {
      $term = $this->createTerm($this->vocabulary);
      $terms[$term->tid] = $term;
    }
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term');
    $result = $query->execute();
    $result = $result['taxonomy_term'];
    asort($result);
    $this->assertEqual(array_keys($terms), array_keys($result), 'Taxonomy terms were retrieved by EntityFieldQuery.');

    // Create a second vocabulary and five more terms.
    $vocabulary2 = $this->createVocabulary();
    $terms2 = array();
    for ($i = 0; $i < 5; $i++) {
      $term = $this->createTerm($vocabulary2);
      $terms2[$term->tid] = $term;
    }

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'taxonomy_term');
    $query->entityCondition('bundle', $vocabulary2->machine_name);
    $result = $query->execute();
    $result = $result['taxonomy_term'];
    asort($result);
    $this->assertEqual(array_keys($terms2), array_keys($result), format_string('Taxonomy terms from the %name vocabulary were retrieved by EntityFieldQuery.', array('%name' => $vocabulary2->name)));
  }

}