taxonomy.test 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980
  1. <?php
  2. /**
  3. * @file
  4. * Tests for taxonomy.module.
  5. */
  6. /**
  7. * Provides common helper methods for Taxonomy module tests.
  8. */
  9. class TaxonomyWebTestCase extends DrupalWebTestCase {
  10. /**
  11. * Returns a new vocabulary with random properties.
  12. */
  13. function createVocabulary() {
  14. // Create a vocabulary.
  15. $vocabulary = new stdClass();
  16. $vocabulary->name = $this->randomName();
  17. $vocabulary->description = $this->randomName();
  18. $vocabulary->machine_name = drupal_strtolower($this->randomName());
  19. $vocabulary->help = '';
  20. $vocabulary->nodes = array('article' => 'article');
  21. $vocabulary->weight = mt_rand(0, 10);
  22. taxonomy_vocabulary_save($vocabulary);
  23. return $vocabulary;
  24. }
  25. /**
  26. * Returns a new term with random properties in vocabulary $vid.
  27. */
  28. function createTerm($vocabulary) {
  29. $term = new stdClass();
  30. $term->name = $this->randomName();
  31. $term->description = $this->randomName();
  32. // Use the first available text format.
  33. $term->format = db_query_range('SELECT format FROM {filter_format}', 0, 1)->fetchField();
  34. $term->vid = $vocabulary->vid;
  35. taxonomy_term_save($term);
  36. return $term;
  37. }
  38. }
  39. /**
  40. * Tests the taxonomy vocabulary interface.
  41. */
  42. class TaxonomyVocabularyFunctionalTest extends TaxonomyWebTestCase {
  43. public static function getInfo() {
  44. return array(
  45. 'name' => 'Taxonomy vocabulary interface',
  46. 'description' => 'Test the taxonomy vocabulary interface.',
  47. 'group' => 'Taxonomy',
  48. );
  49. }
  50. function setUp() {
  51. parent::setUp();
  52. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
  53. $this->drupalLogin($this->admin_user);
  54. $this->vocabulary = $this->createVocabulary();
  55. }
  56. /**
  57. * Create, edit and delete a vocabulary via the user interface.
  58. */
  59. function testVocabularyInterface() {
  60. // Visit the main taxonomy administration page.
  61. $this->drupalGet('admin/structure/taxonomy');
  62. // Create a new vocabulary.
  63. $this->clickLink(t('Add vocabulary'));
  64. $edit = array();
  65. $machine_name = drupal_strtolower($this->randomName());
  66. $edit['name'] = $this->randomName();
  67. $edit['description'] = $this->randomName();
  68. $edit['machine_name'] = $machine_name;
  69. $this->drupalPost(NULL, $edit, t('Save'));
  70. $this->assertRaw(t('Created new vocabulary %name.', array('%name' => $edit['name'])), 'Vocabulary created successfully.');
  71. // Edit the vocabulary.
  72. $this->drupalGet('admin/structure/taxonomy');
  73. $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');
  74. $this->clickLink(t('edit vocabulary'));
  75. $edit = array();
  76. $edit['name'] = $this->randomName();
  77. $this->drupalPost(NULL, $edit, t('Save'));
  78. $this->drupalGet('admin/structure/taxonomy');
  79. $this->assertText($edit['name'], 'Vocabulary found in the vocabulary overview listing.');
  80. // Try to submit a vocabulary with a duplicate machine name.
  81. $edit['machine_name'] = $machine_name;
  82. $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
  83. $this->assertText(t('The machine-readable name is already in use. It must be unique.'));
  84. // Try to submit an invalid machine name.
  85. $edit['machine_name'] = '!&^%';
  86. $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
  87. $this->assertText(t('The machine-readable name must contain only lowercase letters, numbers, and underscores.'));
  88. // Ensure that vocabulary titles are escaped properly.
  89. $edit = array();
  90. $edit['name'] = 'Don\'t Panic';
  91. $edit['description'] = $this->randomName();
  92. $edit['machine_name'] = 'don_t_panic';
  93. $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
  94. $site_name = variable_get('site_name', 'Drupal');
  95. $this->drupalGet('admin/structure/taxonomy/don_t_panic');
  96. $this->assertTitle(t('Don\'t Panic | @site-name', array('@site-name' => $site_name)));
  97. $this->assertNoTitle(t('Don&#039;t Panic | @site-name', array('@site-name' => $site_name)));
  98. }
  99. /**
  100. * Changing weights on the vocabulary overview with two or more vocabularies.
  101. */
  102. function testTaxonomyAdminChangingWeights() {
  103. // Create some vocabularies.
  104. for ($i = 0; $i < 10; $i++) {
  105. $this->createVocabulary();
  106. }
  107. // Get all vocabularies and change their weights.
  108. $vocabularies = taxonomy_get_vocabularies();
  109. $edit = array();
  110. foreach ($vocabularies as $key => $vocabulary) {
  111. $vocabulary->weight = -$vocabulary->weight;
  112. $vocabularies[$key]->weight = $vocabulary->weight;
  113. $edit[$key . '[weight]'] = $vocabulary->weight;
  114. }
  115. // Saving the new weights via the interface.
  116. $this->drupalPost('admin/structure/taxonomy', $edit, t('Save'));
  117. // Load the vocabularies from the database.
  118. $new_vocabularies = taxonomy_get_vocabularies();
  119. // Check that the weights are saved in the database correctly.
  120. foreach ($vocabularies as $key => $vocabulary) {
  121. $this->assertEqual($new_vocabularies[$key]->weight, $vocabularies[$key]->weight, 'The vocabulary weight was changed.');
  122. }
  123. }
  124. /**
  125. * Test the vocabulary overview with no vocabularies.
  126. */
  127. function testTaxonomyAdminNoVocabularies() {
  128. // Delete all vocabularies.
  129. $vocabularies = taxonomy_get_vocabularies();
  130. foreach ($vocabularies as $key => $vocabulary) {
  131. taxonomy_vocabulary_delete($key);
  132. }
  133. // Confirm that no vocabularies are found in the database.
  134. $this->assertFalse(taxonomy_get_vocabularies(), 'No vocabularies found in the database.');
  135. $this->drupalGet('admin/structure/taxonomy');
  136. // Check the default message for no vocabularies.
  137. $this->assertText(t('No vocabularies available.'), 'No vocabularies were found.');
  138. }
  139. /**
  140. * Deleting a vocabulary.
  141. */
  142. function testTaxonomyAdminDeletingVocabulary() {
  143. // Create a vocabulary.
  144. $edit = array(
  145. 'name' => $this->randomName(),
  146. 'machine_name' => drupal_strtolower($this->randomName()),
  147. );
  148. $this->drupalPost('admin/structure/taxonomy/add', $edit, t('Save'));
  149. $this->assertText(t('Created new vocabulary'), 'New vocabulary was created.');
  150. // Check the created vocabulary.
  151. $vocabularies = taxonomy_get_vocabularies();
  152. $vocabularies_keys = array_keys($vocabularies);
  153. $vid = $vocabularies[end($vocabularies_keys)]->vid;
  154. entity_get_controller('taxonomy_vocabulary')->resetCache();
  155. $vocabulary = taxonomy_vocabulary_load($vid);
  156. $this->assertTrue($vocabulary, 'Vocabulary found in database.');
  157. // Delete the vocabulary.
  158. $edit = array();
  159. $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/edit', $edit, t('Delete'));
  160. $this->assertRaw(t('Are you sure you want to delete the vocabulary %name?', array('%name' => $vocabulary->name)), '[confirm deletion] Asks for confirmation.');
  161. $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.');
  162. // Confirm deletion.
  163. $this->drupalPost(NULL, NULL, t('Delete'));
  164. $this->assertRaw(t('Deleted vocabulary %name.', array('%name' => $vocabulary->name)), 'Vocabulary deleted.');
  165. entity_get_controller('taxonomy_vocabulary')->resetCache();
  166. $this->assertFalse(taxonomy_vocabulary_load($vid), 'Vocabulary is not found in the database.');
  167. }
  168. }
  169. /**
  170. * Tests for taxonomy vocabulary functions.
  171. */
  172. class TaxonomyVocabularyTestCase extends TaxonomyWebTestCase {
  173. public static function getInfo() {
  174. return array(
  175. 'name' => 'Taxonomy vocabularies',
  176. 'description' => 'Test loading, saving and deleting vocabularies.',
  177. 'group' => 'Taxonomy',
  178. );
  179. }
  180. function setUp() {
  181. parent::setUp('taxonomy', 'field_test');
  182. $admin_user = $this->drupalCreateUser(array('create article content', 'administer taxonomy'));
  183. $this->drupalLogin($admin_user);
  184. $this->vocabulary = $this->createVocabulary();
  185. }
  186. /**
  187. * Ensure that when an invalid vocabulary vid is loaded, it is possible
  188. * to load the same vid successfully if it subsequently becomes valid.
  189. */
  190. function testTaxonomyVocabularyLoadReturnFalse() {
  191. // Load a vocabulary that doesn't exist.
  192. $vocabularies = taxonomy_get_vocabularies();
  193. $vid = count($vocabularies) + 1;
  194. $vocabulary = taxonomy_vocabulary_load($vid);
  195. // This should not return an object because no such vocabulary exists.
  196. $this->assertTrue(empty($vocabulary), 'No object loaded.');
  197. // Create a new vocabulary.
  198. $this->createVocabulary();
  199. // Load the vocabulary with the same $vid from earlier.
  200. // This should return a vocabulary object since it now matches a real vid.
  201. $vocabulary = taxonomy_vocabulary_load($vid);
  202. $this->assertTrue(!empty($vocabulary) && is_object($vocabulary), 'Vocabulary is an object.');
  203. $this->assertEqual($vocabulary->vid, $vid, 'Valid vocabulary vid is the same as our previously invalid one.');
  204. }
  205. /**
  206. * Test deleting a taxonomy that contains terms.
  207. */
  208. function testTaxonomyVocabularyDeleteWithTerms() {
  209. // Delete any existing vocabularies.
  210. foreach (taxonomy_get_vocabularies() as $vocabulary) {
  211. taxonomy_vocabulary_delete($vocabulary->vid);
  212. }
  213. // Assert that there are no terms left.
  214. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
  215. // Create a new vocabulary and add a few terms to it.
  216. $vocabulary = $this->createVocabulary();
  217. $terms = array();
  218. for ($i = 0; $i < 5; $i++) {
  219. $terms[$i] = $this->createTerm($vocabulary);
  220. }
  221. // Set up hierarchy. term 2 is a child of 1 and 4 a child of 1 and 2.
  222. $terms[2]->parent = array($terms[1]->tid);
  223. taxonomy_term_save($terms[2]);
  224. $terms[4]->parent = array($terms[1]->tid, $terms[2]->tid);
  225. taxonomy_term_save($terms[4]);
  226. // Assert that there are now 5 terms.
  227. $this->assertEqual(5, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
  228. taxonomy_vocabulary_delete($vocabulary->vid);
  229. // Assert that there are no terms left.
  230. $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {taxonomy_term_data}')->fetchField());
  231. }
  232. /**
  233. * Ensure that the vocabulary static reset works correctly.
  234. */
  235. function testTaxonomyVocabularyLoadStaticReset() {
  236. $original_vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
  237. $this->assertTrue(is_object($original_vocabulary), 'Vocabulary loaded successfully.');
  238. $this->assertEqual($this->vocabulary->name, $original_vocabulary->name, 'Vocabulary loaded successfully.');
  239. // Change the name and description.
  240. $vocabulary = $original_vocabulary;
  241. $vocabulary->name = $this->randomName();
  242. $vocabulary->description = $this->randomName();
  243. taxonomy_vocabulary_save($vocabulary);
  244. // Load the vocabulary.
  245. $new_vocabulary = taxonomy_vocabulary_load($original_vocabulary->vid);
  246. $this->assertEqual($new_vocabulary->name, $vocabulary->name);
  247. $this->assertEqual($new_vocabulary->name, $vocabulary->name);
  248. // Delete the vocabulary.
  249. taxonomy_vocabulary_delete($this->vocabulary->vid);
  250. $vocabularies = taxonomy_get_vocabularies();
  251. $this->assertTrue(!isset($vocabularies[$this->vocabulary->vid]), 'The vocabulary was deleted.');
  252. }
  253. /**
  254. * Tests for loading multiple vocabularies.
  255. */
  256. function testTaxonomyVocabularyLoadMultiple() {
  257. // Delete any existing vocabularies.
  258. foreach (taxonomy_get_vocabularies() as $vocabulary) {
  259. taxonomy_vocabulary_delete($vocabulary->vid);
  260. }
  261. // Create some vocabularies and assign weights.
  262. $vocabulary1 = $this->createVocabulary();
  263. $vocabulary1->weight = 0;
  264. taxonomy_vocabulary_save($vocabulary1);
  265. $vocabulary2 = $this->createVocabulary();
  266. $vocabulary2->weight = 1;
  267. taxonomy_vocabulary_save($vocabulary2);
  268. $vocabulary3 = $this->createVocabulary();
  269. $vocabulary3->weight = 2;
  270. taxonomy_vocabulary_save($vocabulary3);
  271. // Fetch the names for all vocabularies, confirm that they are keyed by
  272. // machine name.
  273. $names = taxonomy_vocabulary_get_names();
  274. $this->assertEqual($names[$vocabulary1->machine_name]->name, $vocabulary1->name, 'Vocabulary 1 name found.');
  275. // Fetch all of the vocabularies using taxonomy_get_vocabularies().
  276. // Confirm that the vocabularies are ordered by weight.
  277. $vocabularies = taxonomy_get_vocabularies();
  278. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary was found in the vocabularies array.');
  279. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary was found in the vocabularies array.');
  280. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary was found in the vocabularies array.');
  281. // Fetch the vocabularies with taxonomy_vocabulary_load_multiple(), specifying IDs.
  282. // Ensure they are returned in the same order as the original array.
  283. $vocabularies = taxonomy_vocabulary_load_multiple(array($vocabulary3->vid, $vocabulary2->vid, $vocabulary1->vid));
  284. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary3->vid, 'Vocabulary loaded successfully by ID.');
  285. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary2->vid, 'Vocabulary loaded successfully by ID.');
  286. $this->assertEqual(array_shift($vocabularies)->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by ID.');
  287. // Fetch vocabulary 1 by name.
  288. $vocabulary = current(taxonomy_vocabulary_load_multiple(array(), array('name' => $vocabulary1->name)));
  289. $this->assertEqual($vocabulary->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name.');
  290. // Fetch vocabulary 1 by name and ID.
  291. $this->assertEqual(current(taxonomy_vocabulary_load_multiple(array($vocabulary1->vid), array('name' => $vocabulary1->name)))->vid, $vocabulary1->vid, 'Vocabulary loaded successfully by name and ID.');
  292. }
  293. /**
  294. * Tests that machine name changes are properly reflected.
  295. */
  296. function testTaxonomyVocabularyChangeMachineName() {
  297. // Add a field instance to the vocabulary.
  298. $field = array(
  299. 'field_name' => 'field_test',
  300. 'type' => 'test_field',
  301. );
  302. field_create_field($field);
  303. $instance = array(
  304. 'field_name' => 'field_test',
  305. 'entity_type' => 'taxonomy_term',
  306. 'bundle' => $this->vocabulary->machine_name,
  307. );
  308. field_create_instance($instance);
  309. // Change the machine name.
  310. $new_name = drupal_strtolower($this->randomName());
  311. $this->vocabulary->machine_name = $new_name;
  312. taxonomy_vocabulary_save($this->vocabulary);
  313. // Check that the field instance is still attached to the vocabulary.
  314. $this->assertTrue(field_info_instance('taxonomy_term', 'field_test', $new_name), 'The bundle name was updated correctly.');
  315. }
  316. /**
  317. * Test uninstall and reinstall of the taxonomy module.
  318. */
  319. function testUninstallReinstall() {
  320. // Fields and field instances attached to taxonomy term bundles should be
  321. // removed when the module is uninstalled.
  322. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  323. $this->field = array('field_name' => $this->field_name, 'type' => 'text', 'cardinality' => 4);
  324. $this->field = field_create_field($this->field);
  325. $this->instance = array(
  326. 'field_name' => $this->field_name,
  327. 'entity_type' => 'taxonomy_term',
  328. 'bundle' => $this->vocabulary->machine_name,
  329. 'label' => $this->randomName() . '_label',
  330. );
  331. field_create_instance($this->instance);
  332. module_disable(array('taxonomy'));
  333. require_once DRUPAL_ROOT . '/includes/install.inc';
  334. drupal_uninstall_modules(array('taxonomy'));
  335. module_enable(array('taxonomy'));
  336. // Now create a vocabulary with the same name. All field instances
  337. // connected to this vocabulary name should have been removed when the
  338. // module was uninstalled. Creating a new field with the same name and
  339. // an instance of this field on the same bundle name should be successful.
  340. unset($this->vocabulary->vid);
  341. taxonomy_vocabulary_save($this->vocabulary);
  342. unset($this->field['id']);
  343. field_create_field($this->field);
  344. field_create_instance($this->instance);
  345. }
  346. }
  347. /**
  348. * Unit tests for taxonomy term functions.
  349. */
  350. class TaxonomyTermFunctionTestCase extends TaxonomyWebTestCase {
  351. public static function getInfo() {
  352. return array(
  353. 'name' => 'Taxonomy term unit tests',
  354. 'description' => 'Unit tests for taxonomy term functions.',
  355. 'group' => 'Taxonomy',
  356. );
  357. }
  358. function testTermDelete() {
  359. $vocabulary = $this->createVocabulary();
  360. $valid_term = $this->createTerm($vocabulary);
  361. // Delete a valid term.
  362. taxonomy_term_delete($valid_term->tid);
  363. $terms = taxonomy_term_load_multiple(array(), array('vid' => $vocabulary->vid));
  364. $this->assertTrue(empty($terms), 'Vocabulary is empty after deletion.');
  365. // Delete an invalid term. Should not throw any notices.
  366. taxonomy_term_delete(42);
  367. }
  368. /**
  369. * Test a taxonomy with terms that have multiple parents of different depths.
  370. */
  371. function testTaxonomyVocabularyTree() {
  372. // Create a new vocabulary with 6 terms.
  373. $vocabulary = $this->createVocabulary();
  374. $term = array();
  375. for ($i = 0; $i < 6; $i++) {
  376. $term[$i] = $this->createTerm($vocabulary);
  377. }
  378. // $term[2] is a child of 1 and 5.
  379. $term[2]->parent = array($term[1]->tid, $term[5]->tid);
  380. taxonomy_term_save($term[2]);
  381. // $term[3] is a child of 2.
  382. $term[3]->parent = array($term[2]->tid);
  383. taxonomy_term_save($term[3]);
  384. // $term[5] is a child of 4.
  385. $term[5]->parent = array($term[4]->tid);
  386. taxonomy_term_save($term[5]);
  387. /**
  388. * Expected tree:
  389. * term[0] | depth: 0
  390. * term[1] | depth: 0
  391. * -- term[2] | depth: 1
  392. * ---- term[3] | depth: 2
  393. * term[4] | depth: 0
  394. * -- term[5] | depth: 1
  395. * ---- term[2] | depth: 2
  396. * ------ term[3] | depth: 3
  397. */
  398. // Count $term[1] parents with $max_depth = 1.
  399. $tree = taxonomy_get_tree($vocabulary->vid, $term[1]->tid, 1);
  400. $this->assertEqual(1, count($tree), 'We have one parent with depth 1.');
  401. // Count all vocabulary tree elements.
  402. $tree = taxonomy_get_tree($vocabulary->vid);
  403. $this->assertEqual(8, count($tree), 'We have all vocabulary tree elements.');
  404. // Count elements in every tree depth.
  405. foreach ($tree as $element) {
  406. if (!isset($depth_count[$element->depth])) {
  407. $depth_count[$element->depth] = 0;
  408. }
  409. $depth_count[$element->depth]++;
  410. }
  411. $this->assertEqual(3, $depth_count[0], 'Three elements in taxonomy tree depth 0.');
  412. $this->assertEqual(2, $depth_count[1], 'Two elements in taxonomy tree depth 1.');
  413. $this->assertEqual(2, $depth_count[2], 'Two elements in taxonomy tree depth 2.');
  414. $this->assertEqual(1, $depth_count[3], 'One element in taxonomy tree depth 3.');
  415. }
  416. }
  417. /**
  418. * Test for legacy node bug.
  419. */
  420. class TaxonomyLegacyTestCase extends TaxonomyWebTestCase {
  421. public static function getInfo() {
  422. return array(
  423. 'name' => 'Test for legacy node bug.',
  424. 'description' => 'Posts an article with a taxonomy term and a date prior to 1970.',
  425. 'group' => 'Taxonomy',
  426. );
  427. }
  428. function setUp() {
  429. parent::setUp('taxonomy');
  430. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'administer nodes', 'bypass node access'));
  431. $this->drupalLogin($this->admin_user);
  432. }
  433. /**
  434. * Test taxonomy functionality with nodes prior to 1970.
  435. */
  436. function testTaxonomyLegacyNode() {
  437. // Posts an article with a taxonomy term and a date prior to 1970.
  438. $langcode = LANGUAGE_NONE;
  439. $edit = array();
  440. $edit['title'] = $this->randomName();
  441. $edit['date'] = '1969-01-01 00:00:00 -0500';
  442. $edit["body[$langcode][0][value]"] = $this->randomName();
  443. $edit["field_tags[$langcode]"] = $this->randomName();
  444. $this->drupalPost('node/add/article', $edit, t('Save'));
  445. // Checks that the node has been saved.
  446. $node = $this->drupalGetNodeByTitle($edit['title']);
  447. $this->assertEqual($node->created, strtotime($edit['date']), 'Legacy node was saved with the right date.');
  448. }
  449. }
  450. /**
  451. * Tests for taxonomy term functions.
  452. */
  453. class TaxonomyTermTestCase extends TaxonomyWebTestCase {
  454. public static function getInfo() {
  455. return array(
  456. 'name' => 'Taxonomy term functions and forms.',
  457. 'description' => 'Test load, save and delete for taxonomy terms.',
  458. 'group' => 'Taxonomy',
  459. );
  460. }
  461. function setUp() {
  462. parent::setUp('taxonomy');
  463. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
  464. $this->drupalLogin($this->admin_user);
  465. $this->vocabulary = $this->createVocabulary();
  466. $field = array(
  467. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  468. 'type' => 'taxonomy_term_reference',
  469. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  470. 'settings' => array(
  471. 'allowed_values' => array(
  472. array(
  473. 'vocabulary' => $this->vocabulary->machine_name,
  474. 'parent' => 0,
  475. ),
  476. ),
  477. ),
  478. );
  479. field_create_field($field);
  480. $this->instance = array(
  481. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  482. 'bundle' => 'article',
  483. 'entity_type' => 'node',
  484. 'widget' => array(
  485. 'type' => 'options_select',
  486. ),
  487. 'display' => array(
  488. 'default' => array(
  489. 'type' => 'taxonomy_term_reference_link',
  490. ),
  491. ),
  492. );
  493. field_create_instance($this->instance);
  494. }
  495. /**
  496. * Test terms in a single and multiple hierarchy.
  497. */
  498. function testTaxonomyTermHierarchy() {
  499. // Create two taxonomy terms.
  500. $term1 = $this->createTerm($this->vocabulary);
  501. $term2 = $this->createTerm($this->vocabulary);
  502. // Check that hierarchy is flat.
  503. $vocabulary = taxonomy_vocabulary_load($this->vocabulary->vid);
  504. $this->assertEqual(0, $vocabulary->hierarchy, 'Vocabulary is flat.');
  505. // Edit $term2, setting $term1 as parent.
  506. $edit = array();
  507. $edit['parent[]'] = array($term1->tid);
  508. $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));
  509. // Check the hierarchy.
  510. $children = taxonomy_get_children($term1->tid);
  511. $parents = taxonomy_get_parents($term2->tid);
  512. $this->assertTrue(isset($children[$term2->tid]), 'Child found correctly.');
  513. $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');
  514. // Load and save a term, confirming that parents are still set.
  515. $term = taxonomy_term_load($term2->tid);
  516. taxonomy_term_save($term);
  517. $parents = taxonomy_get_parents($term2->tid);
  518. $this->assertTrue(isset($parents[$term1->tid]), 'Parent found correctly.');
  519. // Create a third term and save this as a parent of term2.
  520. $term3 = $this->createTerm($this->vocabulary);
  521. $term2->parent = array($term1->tid, $term3->tid);
  522. taxonomy_term_save($term2);
  523. $parents = taxonomy_get_parents($term2->tid);
  524. $this->assertTrue(isset($parents[$term1->tid]) && isset($parents[$term3->tid]), 'Both parents found successfully.');
  525. }
  526. /**
  527. * Test that hook_node_$op implementations work correctly.
  528. *
  529. * Save & edit a node and assert that taxonomy terms are saved/loaded properly.
  530. */
  531. function testTaxonomyNode() {
  532. // Create two taxonomy terms.
  533. $term1 = $this->createTerm($this->vocabulary);
  534. $term2 = $this->createTerm($this->vocabulary);
  535. // Post an article.
  536. $edit = array();
  537. $langcode = LANGUAGE_NONE;
  538. $edit["title"] = $this->randomName();
  539. $edit["body[$langcode][0][value]"] = $this->randomName();
  540. $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
  541. $this->drupalPost('node/add/article', $edit, t('Save'));
  542. // Check that the term is displayed when the node is viewed.
  543. $node = $this->drupalGetNodeByTitle($edit["title"]);
  544. $this->drupalGet('node/' . $node->nid);
  545. $this->assertText($term1->name, 'Term is displayed when viewing the node.');
  546. // Edit the node with a different term.
  547. $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term2->tid;
  548. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  549. $this->drupalGet('node/' . $node->nid);
  550. $this->assertText($term2->name, 'Term is displayed when viewing the node.');
  551. // Preview the node.
  552. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Preview'));
  553. $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node.');
  554. $this->drupalPost(NULL, NULL, t('Preview'));
  555. $this->assertNoUniqueText($term2->name, 'Term is displayed when previewing the node again.');
  556. }
  557. /**
  558. * Test term creation with a free-tagging vocabulary from the node form.
  559. */
  560. function testNodeTermCreationAndDeletion() {
  561. // Enable tags in the vocabulary.
  562. $instance = $this->instance;
  563. $instance['widget'] = array('type' => 'taxonomy_autocomplete');
  564. $instance['bundle'] = 'page';
  565. field_create_instance($instance);
  566. $terms = array(
  567. 'term1' => $this->randomName(),
  568. 'term2' => $this->randomName() . ', ' . $this->randomName(),
  569. 'term3' => $this->randomName(),
  570. );
  571. $edit = array();
  572. $langcode = LANGUAGE_NONE;
  573. $edit["title"] = $this->randomName();
  574. $edit["body[$langcode][0][value]"] = $this->randomName();
  575. // Insert the terms in a comma separated list. Vocabulary 1 is a
  576. // free-tagging field created by the default profile.
  577. $edit[$instance['field_name'] . "[$langcode]"] = drupal_implode_tags($terms);
  578. // Preview and verify the terms appear but are not created.
  579. $this->drupalPost('node/add/page', $edit, t('Preview'));
  580. foreach ($terms as $term) {
  581. $this->assertText($term, 'The term appears on the node preview.');
  582. }
  583. $tree = taxonomy_get_tree($this->vocabulary->vid);
  584. $this->assertTrue(empty($tree), 'The terms are not created on preview.');
  585. // taxonomy.module does not maintain its static caches.
  586. drupal_static_reset();
  587. // Save, creating the terms.
  588. $this->drupalPost('node/add/page', $edit, t('Save'));
  589. $this->assertRaw(t('@type %title has been created.', array('@type' => t('Basic page'), '%title' => $edit["title"])), 'The node was created successfully.');
  590. foreach ($terms as $term) {
  591. $this->assertText($term, 'The term was saved and appears on the node page.');
  592. }
  593. // Get the created terms.
  594. $term_objects = array();
  595. foreach ($terms as $key => $term) {
  596. $term_objects[$key] = taxonomy_get_term_by_name($term);
  597. $term_objects[$key] = reset($term_objects[$key]);
  598. }
  599. // Delete term 1.
  600. $this->drupalPost('taxonomy/term/' . $term_objects['term1']->tid . '/edit', array(), t('Delete'));
  601. $this->drupalPost(NULL, NULL, t('Delete'));
  602. $term_names = array($term_objects['term2']->name, $term_objects['term3']->name);
  603. // Get the node.
  604. $node = $this->drupalGetNodeByTitle($edit["title"]);
  605. $this->drupalGet('node/' . $node->nid);
  606. foreach ($term_names as $term_name) {
  607. $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)));
  608. }
  609. $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)));
  610. // Test autocomplete on term 2, which contains a comma.
  611. // The term will be quoted, and the " will be encoded in unicode (\u0022).
  612. $input = substr($term_objects['term2']->name, 0, 3);
  613. $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
  614. $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)));
  615. // Test autocomplete on term 3 - it is alphanumeric only, so no extra
  616. // quoting.
  617. $input = substr($term_objects['term3']->name, 0, 3);
  618. $this->drupalGet('taxonomy/autocomplete/taxonomy_' . $this->vocabulary->machine_name . '/' . $input);
  619. $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)));
  620. // Test taxonomy autocomplete with a nonexistent field.
  621. $field_name = $this->randomName();
  622. $tag = $this->randomName();
  623. $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
  624. $this->assertFalse(field_info_field($field_name), format_string('Field %field_name does not exist.', array('%field_name' => $field_name)));
  625. $this->drupalGet('taxonomy/autocomplete/' . $field_name . '/' . $tag);
  626. $this->assertRaw($message, 'Autocomplete returns correct error message when the taxonomy field does not exist.');
  627. // Test the autocomplete path without passing a field_name and terms.
  628. // This should not trigger a PHP notice.
  629. $field_name = '';
  630. $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
  631. $this->drupalGet('taxonomy/autocomplete');
  632. $this->assertRaw($message, 'Autocomplete returns correct error message when no taxonomy field is given.');
  633. }
  634. /**
  635. * Tests term autocompletion edge cases with slashes in the names.
  636. */
  637. function testTermAutocompletion() {
  638. // Add a term with a slash in the name.
  639. $first_term = $this->createTerm($this->vocabulary);
  640. $first_term->name = '10/16/2011';
  641. taxonomy_term_save($first_term);
  642. // Add another term that differs after the slash character.
  643. $second_term = $this->createTerm($this->vocabulary);
  644. $second_term->name = '10/17/2011';
  645. taxonomy_term_save($second_term);
  646. // Add another term that has both a comma and a slash character.
  647. $third_term = $this->createTerm($this->vocabulary);
  648. $third_term->name = 'term with, a comma and / a slash';
  649. taxonomy_term_save($third_term);
  650. // Try to autocomplete a term name that matches both terms.
  651. // We should get both term in a json encoded string.
  652. $input = '10/';
  653. $path = 'taxonomy/autocomplete/taxonomy_';
  654. $path .= $this->vocabulary->machine_name . '/' . $input;
  655. // The result order is not guaranteed, so check each term separately.
  656. $url = url($path, array('absolute' => TRUE));
  657. $result = drupal_http_request($url);
  658. $data = drupal_json_decode($result->data);
  659. $this->assertEqual($data[$first_term->name], check_plain($first_term->name), 'Autocomplete returned the first matching term.');
  660. $this->assertEqual($data[$second_term->name], check_plain($second_term->name), 'Autocomplete returned the second matching term.');
  661. // Try to autocomplete a term name that matches first term.
  662. // We should only get the first term in a json encoded string.
  663. $input = '10/16';
  664. $url = 'taxonomy/autocomplete/taxonomy_';
  665. $url .= $this->vocabulary->machine_name . '/' . $input;
  666. $this->drupalGet($url);
  667. $target = array($first_term->name => check_plain($first_term->name));
  668. $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');
  669. // Try to autocomplete a term name with both a comma and a slash.
  670. $input = '"term with, comma and / a';
  671. $url = 'taxonomy/autocomplete/taxonomy_';
  672. $url .= $this->vocabulary->machine_name . '/' . $input;
  673. $this->drupalGet($url);
  674. $n = $third_term->name;
  675. // Term names containing commas or quotes must be wrapped in quotes.
  676. if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
  677. $n = '"' . str_replace('"', '""', $third_term->name) . '"';
  678. }
  679. $target = array($n => check_plain($third_term->name));
  680. $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
  681. }
  682. /**
  683. * Save, edit and delete a term using the user interface.
  684. */
  685. function testTermInterface() {
  686. $edit = array(
  687. 'name' => $this->randomName(12),
  688. 'description[value]' => $this->randomName(100),
  689. );
  690. // Explicitly set the parents field to 'root', to ensure that
  691. // taxonomy_form_term_submit() handles the invalid term ID correctly.
  692. $edit['parent[]'] = array(0);
  693. // Create the term to edit.
  694. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
  695. $terms = taxonomy_get_term_by_name($edit['name']);
  696. $term = reset($terms);
  697. $this->assertNotNull($term, 'Term found in database.');
  698. // Submitting a term takes us to the add page; we need the List page.
  699. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  700. // Test edit link as accessed from Taxonomy administration pages.
  701. // Because Simpletest creates its own database when running tests, we know
  702. // the first edit link found on the listing page is to our term.
  703. $this->clickLink(t('edit'));
  704. $this->assertRaw($edit['name'], 'The randomly generated term name is present.');
  705. $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
  706. $edit = array(
  707. 'name' => $this->randomName(14),
  708. 'description[value]' => $this->randomName(102),
  709. );
  710. // Edit the term.
  711. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
  712. // Check that the term is still present at admin UI after edit.
  713. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  714. $this->assertText($edit['name'], 'The randomly generated term name is present.');
  715. $this->assertLink(t('edit'));
  716. // View the term and check that it is correct.
  717. $this->drupalGet('taxonomy/term/' . $term->tid);
  718. $this->assertText($edit['name'], 'The randomly generated term name is present.');
  719. $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
  720. // Did this page request display a 'term-listing-heading'?
  721. $this->assertPattern('|class="taxonomy-term-description"|', 'Term page displayed the term description element.');
  722. // Check that it does NOT show a description when description is blank.
  723. $term->description = '';
  724. taxonomy_term_save($term);
  725. $this->drupalGet('taxonomy/term/' . $term->tid);
  726. $this->assertNoPattern('|class="taxonomy-term-description"|', 'Term page did not display the term description when description was blank.');
  727. // Check that the term feed page is working.
  728. $this->drupalGet('taxonomy/term/' . $term->tid . '/feed');
  729. // Check that the term edit page does not try to interpret additional path
  730. // components as arguments for taxonomy_form_term().
  731. $this->drupalGet('taxonomy/term/' . $term->tid . '/edit/' . $this->randomName());
  732. // Delete the term.
  733. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', array(), t('Delete'));
  734. $this->drupalPost(NULL, NULL, t('Delete'));
  735. // Assert that the term no longer exists.
  736. $this->drupalGet('taxonomy/term/' . $term->tid);
  737. $this->assertResponse(404, 'The taxonomy term page was not found.');
  738. }
  739. /**
  740. * Save, edit and delete a term using the user interface.
  741. */
  742. function testTermReorder() {
  743. $this->createTerm($this->vocabulary);
  744. $this->createTerm($this->vocabulary);
  745. $this->createTerm($this->vocabulary);
  746. // Fetch the created terms in the default alphabetical order, i.e. term1
  747. // precedes term2 alphabetically, and term2 precedes term3.
  748. drupal_static_reset('taxonomy_get_tree');
  749. drupal_static_reset('taxonomy_get_treeparent');
  750. drupal_static_reset('taxonomy_get_treeterms');
  751. list($term1, $term2, $term3) = taxonomy_get_tree($this->vocabulary->vid);
  752. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  753. // Each term has four hidden fields, "tid:1:0[tid]", "tid:1:0[parent]",
  754. // "tid:1:0[depth]", and "tid:1:0[weight]". Change the order to term2,
  755. // term3, term1 by setting weight property, make term3 a child of term2 by
  756. // setting the parent and depth properties, and update all hidden fields.
  757. $edit = array(
  758. 'tid:' . $term2->tid . ':0[tid]' => $term2->tid,
  759. 'tid:' . $term2->tid . ':0[parent]' => 0,
  760. 'tid:' . $term2->tid . ':0[depth]' => 0,
  761. 'tid:' . $term2->tid . ':0[weight]' => 0,
  762. 'tid:' . $term3->tid . ':0[tid]' => $term3->tid,
  763. 'tid:' . $term3->tid . ':0[parent]' => $term2->tid,
  764. 'tid:' . $term3->tid . ':0[depth]' => 1,
  765. 'tid:' . $term3->tid . ':0[weight]' => 1,
  766. 'tid:' . $term1->tid . ':0[tid]' => $term1->tid,
  767. 'tid:' . $term1->tid . ':0[parent]' => 0,
  768. 'tid:' . $term1->tid . ':0[depth]' => 0,
  769. 'tid:' . $term1->tid . ':0[weight]' => 2,
  770. );
  771. $this->drupalPost(NULL, $edit, t('Save'));
  772. drupal_static_reset('taxonomy_get_tree');
  773. drupal_static_reset('taxonomy_get_treeparent');
  774. drupal_static_reset('taxonomy_get_treeterms');
  775. $terms = taxonomy_get_tree($this->vocabulary->vid);
  776. $this->assertEqual($terms[0]->tid, $term2->tid, 'Term 2 was moved above term 1.');
  777. $this->assertEqual($terms[1]->parents, array($term2->tid), 'Term 3 was made a child of term 2.');
  778. $this->assertEqual($terms[2]->tid, $term1->tid, 'Term 1 was moved below term 2.');
  779. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name, array(), t('Reset to alphabetical'));
  780. // Submit confirmation form.
  781. $this->drupalPost(NULL, array(), t('Reset to alphabetical'));
  782. drupal_static_reset('taxonomy_get_tree');
  783. drupal_static_reset('taxonomy_get_treeparent');
  784. drupal_static_reset('taxonomy_get_treeterms');
  785. $terms = taxonomy_get_tree($this->vocabulary->vid);
  786. $this->assertEqual($terms[0]->tid, $term1->tid, 'Term 1 was moved to back above term 2.');
  787. $this->assertEqual($terms[1]->tid, $term2->tid, 'Term 2 was moved to back below term 1.');
  788. $this->assertEqual($terms[2]->tid, $term3->tid, 'Term 3 is still below term 2.');
  789. $this->assertEqual($terms[2]->parents, array($term2->tid), 'Term 3 is still a child of term 2.' . var_export($terms[1]->tid, 1));
  790. }
  791. /**
  792. * Test saving a term with multiple parents through the UI.
  793. */
  794. function testTermMultipleParentsInterface() {
  795. // Add a new term to the vocabulary so that we can have multiple parents.
  796. $parent = $this->createTerm($this->vocabulary);
  797. // Add a new term with multiple parents.
  798. $edit = array(
  799. 'name' => $this->randomName(12),
  800. 'description[value]' => $this->randomName(100),
  801. 'parent[]' => array(0, $parent->tid),
  802. );
  803. // Save the new term.
  804. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
  805. // Check that the term was successfully created.
  806. $terms = taxonomy_get_term_by_name($edit['name']);
  807. $term = reset($terms);
  808. $this->assertNotNull($term, 'Term found in database.');
  809. $this->assertEqual($edit['name'], $term->name, 'Term name was successfully saved.');
  810. $this->assertEqual($edit['description[value]'], $term->description, 'Term description was successfully saved.');
  811. // Check that the parent tid is still there. The other parent (<root>) is
  812. // not added by taxonomy_get_parents().
  813. $parents = taxonomy_get_parents($term->tid);
  814. $parent = reset($parents);
  815. $this->assertEqual($edit['parent[]'][1], $parent->tid, 'Term parents were successfully saved.');
  816. }
  817. /**
  818. * Test taxonomy_get_term_by_name().
  819. */
  820. function testTaxonomyGetTermByName() {
  821. $term = $this->createTerm($this->vocabulary);
  822. // Load the term with the exact name.
  823. $terms = taxonomy_get_term_by_name($term->name);
  824. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name.');
  825. // Load the term with space concatenated.
  826. $terms = taxonomy_get_term_by_name(' ' . $term->name . ' ');
  827. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with extra whitespace.');
  828. // Load the term with name uppercased.
  829. $terms = taxonomy_get_term_by_name(strtoupper($term->name));
  830. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with uppercased name.');
  831. // Load the term with name lowercased.
  832. $terms = taxonomy_get_term_by_name(strtolower($term->name));
  833. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with lowercased name.');
  834. // Try to load an invalid term name.
  835. $terms = taxonomy_get_term_by_name('Banana');
  836. $this->assertFalse($terms);
  837. // Try to load the term using a substring of the name.
  838. $terms = taxonomy_get_term_by_name(drupal_substr($term->name, 2));
  839. $this->assertFalse($terms);
  840. // Create a new term in a different vocabulary with the same name.
  841. $new_vocabulary = $this->createVocabulary();
  842. $new_term = new stdClass();
  843. $new_term->name = $term->name;
  844. $new_term->vid = $new_vocabulary->vid;
  845. taxonomy_term_save($new_term);
  846. // Load multiple terms with the same name.
  847. $terms = taxonomy_get_term_by_name($term->name);
  848. $this->assertEqual(count($terms), 2, 'Two terms loaded with the same name.');
  849. // Load single term when restricted to one vocabulary.
  850. $terms = taxonomy_get_term_by_name($term->name, $this->vocabulary->machine_name);
  851. $this->assertEqual(count($terms), 1, 'One term loaded when restricted by vocabulary.');
  852. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name and vocabulary machine name.');
  853. // Create a new term with another name.
  854. $term2 = $this->createTerm($this->vocabulary);
  855. // Try to load a term by name that doesn't exist in this vocabulary but
  856. // exists in another vocabulary.
  857. $terms = taxonomy_get_term_by_name($term2->name, $new_vocabulary->machine_name);
  858. $this->assertFalse($terms, 'Invalid term name restricted by vocabulary machine name not loaded.');
  859. // Try to load terms filtering by a non-existing vocabulary.
  860. $terms = taxonomy_get_term_by_name($term2->name, 'non_existing_vocabulary');
  861. $this->assertEqual(count($terms), 0, 'No terms loaded when restricted by a non-existing vocabulary.');
  862. }
  863. }
  864. /**
  865. * Tests the rendering of term reference fields in RSS feeds.
  866. */
  867. class TaxonomyRSSTestCase extends TaxonomyWebTestCase {
  868. public static function getInfo() {
  869. return array(
  870. 'name' => 'Taxonomy RSS Content.',
  871. 'description' => 'Ensure that data added as terms appears in RSS feeds if "RSS Category" format is selected.',
  872. 'group' => 'Taxonomy',
  873. );
  874. }
  875. function setUp() {
  876. parent::setUp('taxonomy');
  877. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access', 'administer content types'));
  878. $this->drupalLogin($this->admin_user);
  879. $this->vocabulary = $this->createVocabulary();
  880. $field = array(
  881. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  882. 'type' => 'taxonomy_term_reference',
  883. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  884. 'settings' => array(
  885. 'allowed_values' => array(
  886. array(
  887. 'vocabulary' => $this->vocabulary->machine_name,
  888. 'parent' => 0,
  889. ),
  890. ),
  891. ),
  892. );
  893. field_create_field($field);
  894. $this->instance = array(
  895. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  896. 'bundle' => 'article',
  897. 'entity_type' => 'node',
  898. 'widget' => array(
  899. 'type' => 'options_select',
  900. ),
  901. 'display' => array(
  902. 'default' => array(
  903. 'type' => 'taxonomy_term_reference_link',
  904. ),
  905. ),
  906. );
  907. field_create_instance($this->instance);
  908. }
  909. /**
  910. * Tests that terms added to nodes are displayed in core RSS feed.
  911. *
  912. * Create a node and assert that taxonomy terms appear in rss.xml.
  913. */
  914. function testTaxonomyRSS() {
  915. // Create two taxonomy terms.
  916. $term1 = $this->createTerm($this->vocabulary);
  917. // RSS display must be added manually.
  918. $this->drupalGet("admin/structure/types/manage/article/display");
  919. $edit = array(
  920. "view_modes_custom[rss]" => '1',
  921. );
  922. $this->drupalPost(NULL, $edit, t('Save'));
  923. // Change the format to 'RSS category'.
  924. $this->drupalGet("admin/structure/types/manage/article/display/rss");
  925. $edit = array(
  926. "fields[taxonomy_" . $this->vocabulary->machine_name . "][type]" => 'taxonomy_term_reference_rss_category',
  927. );
  928. $this->drupalPost(NULL, $edit, t('Save'));
  929. // Post an article.
  930. $edit = array();
  931. $langcode = LANGUAGE_NONE;
  932. $edit["title"] = $this->randomName();
  933. $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
  934. $this->drupalPost('node/add/article', $edit, t('Save'));
  935. // Check that the term is displayed when the RSS feed is viewed.
  936. $this->drupalGet('rss.xml');
  937. $test_element = array(
  938. 'key' => 'category',
  939. 'value' => $term1->name,
  940. 'attributes' => array(
  941. 'domain' => url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE)),
  942. ),
  943. );
  944. $this->assertRaw(format_xml_elements(array($test_element)), 'Term is displayed when viewing the rss feed.');
  945. }
  946. }
  947. /**
  948. * Tests the hook implementations that maintain the taxonomy index.
  949. */
  950. class TaxonomyTermIndexTestCase extends TaxonomyWebTestCase {
  951. public static function getInfo() {
  952. return array(
  953. 'name' => 'Taxonomy term index',
  954. 'description' => 'Tests the hook implementations that maintain the taxonomy index.',
  955. 'group' => 'Taxonomy',
  956. );
  957. }
  958. function setUp() {
  959. parent::setUp('taxonomy');
  960. // Create an administrative user.
  961. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
  962. $this->drupalLogin($this->admin_user);
  963. // Create a vocabulary and add two term reference fields to article nodes.
  964. $this->vocabulary = $this->createVocabulary();
  965. $this->field_name_1 = drupal_strtolower($this->randomName());
  966. $this->field_1 = array(
  967. 'field_name' => $this->field_name_1,
  968. 'type' => 'taxonomy_term_reference',
  969. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  970. 'settings' => array(
  971. 'allowed_values' => array(
  972. array(
  973. 'vocabulary' => $this->vocabulary->machine_name,
  974. 'parent' => 0,
  975. ),
  976. ),
  977. ),
  978. );
  979. field_create_field($this->field_1);
  980. $this->instance_1 = array(
  981. 'field_name' => $this->field_name_1,
  982. 'bundle' => 'article',
  983. 'entity_type' => 'node',
  984. 'widget' => array(
  985. 'type' => 'options_select',
  986. ),
  987. 'display' => array(
  988. 'default' => array(
  989. 'type' => 'taxonomy_term_reference_link',
  990. ),
  991. ),
  992. );
  993. field_create_instance($this->instance_1);
  994. $this->field_name_2 = drupal_strtolower($this->randomName());
  995. $this->field_2 = array(
  996. 'field_name' => $this->field_name_2,
  997. 'type' => 'taxonomy_term_reference',
  998. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  999. 'settings' => array(
  1000. 'allowed_values' => array(
  1001. array(
  1002. 'vocabulary' => $this->vocabulary->machine_name,
  1003. 'parent' => 0,
  1004. ),
  1005. ),
  1006. ),
  1007. );
  1008. field_create_field($this->field_2);
  1009. $this->instance_2 = array(
  1010. 'field_name' => $this->field_name_2,
  1011. 'bundle' => 'article',
  1012. 'entity_type' => 'node',
  1013. 'widget' => array(
  1014. 'type' => 'options_select',
  1015. ),
  1016. 'display' => array(
  1017. 'default' => array(
  1018. 'type' => 'taxonomy_term_reference_link',
  1019. ),
  1020. ),
  1021. );
  1022. field_create_instance($this->instance_2);
  1023. }
  1024. /**
  1025. * Tests that the taxonomy index is maintained properly.
  1026. */
  1027. function testTaxonomyIndex() {
  1028. // Create terms in the vocabulary.
  1029. $term_1 = $this->createTerm($this->vocabulary);
  1030. $term_2 = $this->createTerm($this->vocabulary);
  1031. // Post an article.
  1032. $edit = array();
  1033. $langcode = LANGUAGE_NONE;
  1034. $edit["title"] = $this->randomName();
  1035. $edit["body[$langcode][0][value]"] = $this->randomName();
  1036. $edit["{$this->field_name_1}[$langcode][]"] = $term_1->tid;
  1037. $edit["{$this->field_name_2}[$langcode][]"] = $term_1->tid;
  1038. $this->drupalPost('node/add/article', $edit, t('Save'));
  1039. // Check that the term is indexed, and only once.
  1040. $node = $this->drupalGetNodeByTitle($edit["title"]);
  1041. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1042. ':nid' => $node->nid,
  1043. ':tid' => $term_1->tid,
  1044. ))->fetchField();
  1045. $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
  1046. // Update the article to change one term.
  1047. $edit["{$this->field_name_1}[$langcode][]"] = $term_2->tid;
  1048. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1049. // Check that both terms are indexed.
  1050. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1051. ':nid' => $node->nid,
  1052. ':tid' => $term_1->tid,
  1053. ))->fetchField();
  1054. $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
  1055. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1056. ':nid' => $node->nid,
  1057. ':tid' => $term_2->tid,
  1058. ))->fetchField();
  1059. $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
  1060. // Update the article to change another term.
  1061. $edit["{$this->field_name_2}[$langcode][]"] = $term_2->tid;
  1062. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1063. // Check that only one term is indexed.
  1064. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1065. ':nid' => $node->nid,
  1066. ':tid' => $term_1->tid,
  1067. ))->fetchField();
  1068. $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
  1069. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1070. ':nid' => $node->nid,
  1071. ':tid' => $term_2->tid,
  1072. ))->fetchField();
  1073. $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
  1074. // Redo the above tests without interface.
  1075. $update_node = array(
  1076. 'nid' => $node->nid,
  1077. 'vid' => $node->vid,
  1078. 'uid' => $node->uid,
  1079. 'type' => $node->type,
  1080. 'title' => $this->randomName(),
  1081. );
  1082. // Update the article with no term changed.
  1083. $updated_node = (object) $update_node;
  1084. node_save($updated_node);
  1085. // Check that the index was not changed.
  1086. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1087. ':nid' => $node->nid,
  1088. ':tid' => $term_1->tid,
  1089. ))->fetchField();
  1090. $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
  1091. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1092. ':nid' => $node->nid,
  1093. ':tid' => $term_2->tid,
  1094. ))->fetchField();
  1095. $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
  1096. // Update the article to change one term.
  1097. $update_node[$this->field_name_1][$langcode] = array(array('tid' => $term_1->tid));
  1098. $updated_node = (object) $update_node;
  1099. node_save($updated_node);
  1100. // Check that both terms are indexed.
  1101. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1102. ':nid' => $node->nid,
  1103. ':tid' => $term_1->tid,
  1104. ))->fetchField();
  1105. $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
  1106. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1107. ':nid' => $node->nid,
  1108. ':tid' => $term_2->tid,
  1109. ))->fetchField();
  1110. $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
  1111. // Update the article to change another term.
  1112. $update_node[$this->field_name_2][$langcode] = array(array('tid' => $term_1->tid));
  1113. $updated_node = (object) $update_node;
  1114. node_save($updated_node);
  1115. // Check that only one term is indexed.
  1116. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1117. ':nid' => $node->nid,
  1118. ':tid' => $term_1->tid,
  1119. ))->fetchField();
  1120. $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
  1121. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1122. ':nid' => $node->nid,
  1123. ':tid' => $term_2->tid,
  1124. ))->fetchField();
  1125. $this->assertEqual(0, $index_count, 'Term 2 is not indexed.');
  1126. }
  1127. /**
  1128. * Tests that there is a link to the parent term on the child term page.
  1129. */
  1130. function testTaxonomyTermHierarchyBreadcrumbs() {
  1131. // Create two taxonomy terms and set term2 as the parent of term1.
  1132. $term1 = $this->createTerm($this->vocabulary);
  1133. $term2 = $this->createTerm($this->vocabulary);
  1134. $term1->parent = array($term2->tid);
  1135. taxonomy_term_save($term1);
  1136. // Verify that the page breadcrumbs include a link to the parent term.
  1137. $this->drupalGet('taxonomy/term/' . $term1->tid);
  1138. $this->assertRaw(l($term2->name, 'taxonomy/term/' . $term2->tid), 'Parent term link is displayed when viewing the node.');
  1139. }
  1140. }
  1141. /**
  1142. * Test the taxonomy_term_load_multiple() function.
  1143. */
  1144. class TaxonomyLoadMultipleTestCase extends TaxonomyWebTestCase {
  1145. public static function getInfo() {
  1146. return array(
  1147. 'name' => 'Taxonomy term multiple loading',
  1148. 'description' => 'Test the loading of multiple taxonomy terms at once',
  1149. 'group' => 'Taxonomy',
  1150. );
  1151. }
  1152. function setUp() {
  1153. parent::setUp();
  1154. $this->taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
  1155. $this->drupalLogin($this->taxonomy_admin);
  1156. }
  1157. /**
  1158. * Create a vocabulary and some taxonomy terms, ensuring they're loaded
  1159. * correctly using taxonomy_term_load_multiple().
  1160. */
  1161. function testTaxonomyTermMultipleLoad() {
  1162. // Create a vocabulary.
  1163. $vocabulary = $this->createVocabulary();
  1164. // Create five terms in the vocabulary.
  1165. $i = 0;
  1166. while ($i < 5) {
  1167. $i++;
  1168. $this->createTerm($vocabulary);
  1169. }
  1170. // Load the terms from the vocabulary.
  1171. $terms = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
  1172. $count = count($terms);
  1173. $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. !count terms.', array('!count' => $count)));
  1174. // Load the same terms again by tid.
  1175. $terms2 = taxonomy_term_load_multiple(array_keys($terms));
  1176. $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.');
  1177. $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.');
  1178. // Load the terms by tid, with a condition on vid.
  1179. $terms3 = taxonomy_term_load_multiple(array_keys($terms2), array('vid' => $vocabulary->vid));
  1180. $this->assertEqual($terms2, $terms3);
  1181. // Remove one term from the array, then delete it.
  1182. $deleted = array_shift($terms3);
  1183. taxonomy_term_delete($deleted->tid);
  1184. $deleted_term = taxonomy_term_load($deleted->tid);
  1185. $this->assertFalse($deleted_term);
  1186. // Load terms from the vocabulary by vid.
  1187. $terms4 = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
  1188. $this->assertEqual(count($terms4), 4, 'Correct number of terms were loaded.');
  1189. $this->assertFalse(isset($terms4[$deleted->tid]));
  1190. // Create a single term and load it by name.
  1191. $term = $this->createTerm($vocabulary);
  1192. $loaded_terms = taxonomy_term_load_multiple(array(), array('name' => $term->name));
  1193. $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.');
  1194. $loaded_term = reset($loaded_terms);
  1195. $this->assertEqual($term->tid, $loaded_term->tid, 'Term loaded by name successfully.');
  1196. }
  1197. }
  1198. /**
  1199. * Tests for taxonomy hook invocation.
  1200. */
  1201. class TaxonomyHooksTestCase extends TaxonomyWebTestCase {
  1202. public static function getInfo() {
  1203. return array(
  1204. 'name' => 'Taxonomy term hooks',
  1205. 'description' => 'Hooks for taxonomy term load/save/delete.',
  1206. 'group' => 'Taxonomy',
  1207. );
  1208. }
  1209. function setUp() {
  1210. parent::setUp('taxonomy', 'taxonomy_test');
  1211. module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  1212. $taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
  1213. $this->drupalLogin($taxonomy_admin);
  1214. }
  1215. /**
  1216. * Test that hooks are run correctly on creating, editing, viewing,
  1217. * and deleting a term.
  1218. *
  1219. * @see taxonomy_test.module
  1220. */
  1221. function testTaxonomyTermHooks() {
  1222. $vocabulary = $this->createVocabulary();
  1223. // Create a term with one antonym.
  1224. $edit = array(
  1225. 'name' => $this->randomName(),
  1226. 'antonym' => 'Long',
  1227. );
  1228. $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add', $edit, t('Save'));
  1229. $terms = taxonomy_get_term_by_name($edit['name']);
  1230. $term = reset($terms);
  1231. $this->assertEqual($term->antonym, $edit['antonym'], 'Antonym was loaded into the term object.');
  1232. // Update the term with a different antonym.
  1233. $edit = array(
  1234. 'name' => $this->randomName(),
  1235. 'antonym' => 'Short',
  1236. );
  1237. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
  1238. taxonomy_terms_static_reset();
  1239. $term = taxonomy_term_load($term->tid);
  1240. $this->assertEqual($edit['antonym'], $term->antonym, 'Antonym was successfully edited.');
  1241. // View the term and ensure that hook_taxonomy_term_view() and
  1242. // hook_entity_view() are invoked.
  1243. $term = taxonomy_term_load($term->tid);
  1244. $term_build = taxonomy_term_page($term);
  1245. $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_term_view_check']), 'hook_taxonomy_term_view() was invoked when viewing the term.');
  1246. $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_entity_view_check']), 'hook_entity_view() was invoked when viewing the term.');
  1247. // Delete the term.
  1248. taxonomy_term_delete($term->tid);
  1249. $antonym = db_query('SELECT tid FROM {taxonomy_term_antonym} WHERE tid = :tid', array(':tid' => $term->tid))->fetchField();
  1250. $this->assertFalse($antonym, 'The antonym were deleted from the database.');
  1251. }
  1252. }
  1253. /**
  1254. * Tests for taxonomy term field and formatter.
  1255. */
  1256. class TaxonomyTermFieldTestCase extends TaxonomyWebTestCase {
  1257. protected $instance;
  1258. protected $vocabulary;
  1259. public static function getInfo() {
  1260. return array(
  1261. 'name' => 'Taxonomy term reference field',
  1262. 'description' => 'Test the creation of term fields.',
  1263. 'group' => 'Taxonomy',
  1264. );
  1265. }
  1266. function setUp() {
  1267. parent::setUp('field_test');
  1268. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
  1269. $this->drupalLogin($web_user);
  1270. $this->vocabulary = $this->createVocabulary();
  1271. // Setup a field and instance.
  1272. $this->field_name = drupal_strtolower($this->randomName());
  1273. $this->field = array(
  1274. 'field_name' => $this->field_name,
  1275. 'type' => 'taxonomy_term_reference',
  1276. 'settings' => array(
  1277. 'allowed_values' => array(
  1278. array(
  1279. 'vocabulary' => $this->vocabulary->machine_name,
  1280. 'parent' => '0',
  1281. ),
  1282. ),
  1283. )
  1284. );
  1285. field_create_field($this->field);
  1286. $this->instance = array(
  1287. 'field_name' => $this->field_name,
  1288. 'entity_type' => 'test_entity',
  1289. 'bundle' => 'test_bundle',
  1290. 'widget' => array(
  1291. 'type' => 'options_select',
  1292. ),
  1293. 'display' => array(
  1294. 'full' => array(
  1295. 'type' => 'taxonomy_term_reference_link',
  1296. ),
  1297. ),
  1298. );
  1299. field_create_instance($this->instance);
  1300. }
  1301. /**
  1302. * Test term field validation.
  1303. */
  1304. function testTaxonomyTermFieldValidation() {
  1305. // Test valid and invalid values with field_attach_validate().
  1306. $langcode = LANGUAGE_NONE;
  1307. $entity = field_test_create_stub_entity();
  1308. $term = $this->createTerm($this->vocabulary);
  1309. $entity->{$this->field_name}[$langcode][0]['tid'] = $term->tid;
  1310. try {
  1311. field_attach_validate('test_entity', $entity);
  1312. $this->pass('Correct term does not cause validation error.');
  1313. }
  1314. catch (FieldValidationException $e) {
  1315. $this->fail('Correct term does not cause validation error.');
  1316. }
  1317. $entity = field_test_create_stub_entity();
  1318. $bad_term = $this->createTerm($this->createVocabulary());
  1319. $entity->{$this->field_name}[$langcode][0]['tid'] = $bad_term->tid;
  1320. try {
  1321. field_attach_validate('test_entity', $entity);
  1322. $this->fail('Wrong term causes validation error.');
  1323. }
  1324. catch (FieldValidationException $e) {
  1325. $this->pass('Wrong term causes validation error.');
  1326. }
  1327. }
  1328. /**
  1329. * Test widgets.
  1330. */
  1331. function testTaxonomyTermFieldWidgets() {
  1332. // Create a term in the vocabulary.
  1333. $term = $this->createTerm($this->vocabulary);
  1334. // Display creation form.
  1335. $langcode = LANGUAGE_NONE;
  1336. $this->drupalGet('test-entity/add/test-bundle');
  1337. $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');
  1338. // Submit with some value.
  1339. $edit = array(
  1340. "{$this->field_name}[$langcode]" => array($term->tid),
  1341. );
  1342. $this->drupalPost(NULL, $edit, t('Save'));
  1343. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1344. $id = $match[1];
  1345. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
  1346. // Display the object.
  1347. $entity = field_test_entity_test_load($id);
  1348. $entities = array($id => $entity);
  1349. field_attach_prepare_view('test_entity', $entities, 'full');
  1350. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1351. $this->content = drupal_render($entity->content);
  1352. $this->assertText($term->name, 'Term name is displayed.');
  1353. // Delete the vocabulary and verify that the widget is gone.
  1354. taxonomy_vocabulary_delete($this->vocabulary->vid);
  1355. $this->drupalGet('test-entity/add/test-bundle');
  1356. $this->assertNoFieldByName("{$this->field_name}[$langcode]", '', 'Widget is not displayed.');
  1357. }
  1358. /**
  1359. * Tests that vocabulary machine name changes are mirrored in field definitions.
  1360. */
  1361. function testTaxonomyTermFieldChangeMachineName() {
  1362. // Add several entries in the 'allowed_values' setting, to make sure that
  1363. // they all get updated.
  1364. $this->field['settings']['allowed_values'] = array(
  1365. array(
  1366. 'vocabulary' => $this->vocabulary->machine_name,
  1367. 'parent' => '0',
  1368. ),
  1369. array(
  1370. 'vocabulary' => $this->vocabulary->machine_name,
  1371. 'parent' => '0',
  1372. ),
  1373. array(
  1374. 'vocabulary' => 'foo',
  1375. 'parent' => '0',
  1376. ),
  1377. );
  1378. field_update_field($this->field);
  1379. // Change the machine name.
  1380. $old_name = $this->vocabulary->machine_name;
  1381. $new_name = drupal_strtolower($this->randomName());
  1382. $this->vocabulary->machine_name = $new_name;
  1383. taxonomy_vocabulary_save($this->vocabulary);
  1384. // Check that entity bundles are properly updated.
  1385. $info = entity_get_info('taxonomy_term');
  1386. $this->assertFalse(isset($info['bundles'][$old_name]), 'The old bundle name does not appear in entity_get_info().');
  1387. $this->assertTrue(isset($info['bundles'][$new_name]), 'The new bundle name appears in entity_get_info().');
  1388. // Check that the field instance is still attached to the vocabulary.
  1389. $field = field_info_field($this->field_name);
  1390. $allowed_values = $field['settings']['allowed_values'];
  1391. $this->assertEqual($allowed_values[0]['vocabulary'], $new_name, 'Index 0: Machine name was updated correctly.');
  1392. $this->assertEqual($allowed_values[1]['vocabulary'], $new_name, 'Index 1: Machine name was updated correctly.');
  1393. $this->assertEqual($allowed_values[2]['vocabulary'], 'foo', 'Index 2: Machine name was left untouched.');
  1394. }
  1395. }
  1396. /**
  1397. * Tests a taxonomy term reference field that allows multiple vocabularies.
  1398. */
  1399. class TaxonomyTermFieldMultipleVocabularyTestCase extends TaxonomyWebTestCase {
  1400. protected $instance;
  1401. protected $vocabulary1;
  1402. protected $vocabulary2;
  1403. public static function getInfo() {
  1404. return array(
  1405. 'name' => 'Multiple vocabulary term reference field',
  1406. 'description' => 'Tests term reference fields that allow multiple vocabularies.',
  1407. 'group' => 'Taxonomy',
  1408. );
  1409. }
  1410. function setUp() {
  1411. parent::setUp('field_test');
  1412. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
  1413. $this->drupalLogin($web_user);
  1414. $this->vocabulary1 = $this->createVocabulary();
  1415. $this->vocabulary2 = $this->createVocabulary();
  1416. // Set up a field and instance.
  1417. $this->field_name = drupal_strtolower($this->randomName());
  1418. $this->field = array(
  1419. 'field_name' => $this->field_name,
  1420. 'type' => 'taxonomy_term_reference',
  1421. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1422. 'settings' => array(
  1423. 'allowed_values' => array(
  1424. array(
  1425. 'vocabulary' => $this->vocabulary1->machine_name,
  1426. 'parent' => '0',
  1427. ),
  1428. array(
  1429. 'vocabulary' => $this->vocabulary2->machine_name,
  1430. 'parent' => '0',
  1431. ),
  1432. ),
  1433. )
  1434. );
  1435. field_create_field($this->field);
  1436. $this->instance = array(
  1437. 'field_name' => $this->field_name,
  1438. 'entity_type' => 'test_entity',
  1439. 'bundle' => 'test_bundle',
  1440. 'widget' => array(
  1441. 'type' => 'options_select',
  1442. ),
  1443. 'display' => array(
  1444. 'full' => array(
  1445. 'type' => 'taxonomy_term_reference_link',
  1446. ),
  1447. ),
  1448. );
  1449. field_create_instance($this->instance);
  1450. }
  1451. /**
  1452. * Tests term reference field and widget with multiple vocabularies.
  1453. */
  1454. function testTaxonomyTermFieldMultipleVocabularies() {
  1455. // Create a term in each vocabulary.
  1456. $term1 = $this->createTerm($this->vocabulary1);
  1457. $term2 = $this->createTerm($this->vocabulary2);
  1458. // Submit an entity with both terms.
  1459. $langcode = LANGUAGE_NONE;
  1460. $this->drupalGet('test-entity/add/test-bundle');
  1461. $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is displayed.');
  1462. $edit = array(
  1463. "{$this->field_name}[$langcode][]" => array($term1->tid, $term2->tid),
  1464. );
  1465. $this->drupalPost(NULL, $edit, t('Save'));
  1466. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1467. $id = $match[1];
  1468. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
  1469. // Render the entity.
  1470. $entity = field_test_entity_test_load($id);
  1471. $entities = array($id => $entity);
  1472. field_attach_prepare_view('test_entity', $entities, 'full');
  1473. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1474. $this->content = drupal_render($entity->content);
  1475. $this->assertText($term1->name, 'Term 1 name is displayed.');
  1476. $this->assertText($term2->name, 'Term 2 name is displayed.');
  1477. // Delete vocabulary 2.
  1478. taxonomy_vocabulary_delete($this->vocabulary2->vid);
  1479. // Re-render the content.
  1480. $entity = field_test_entity_test_load($id);
  1481. $entities = array($id => $entity);
  1482. field_attach_prepare_view('test_entity', $entities, 'full');
  1483. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1484. $this->plainTextContent = FALSE;
  1485. $this->content = drupal_render($entity->content);
  1486. // Term 1 should still be displayed; term 2 should not be.
  1487. $this->assertText($term1->name, 'Term 1 name is displayed.');
  1488. $this->assertNoText($term2->name, 'Term 2 name is not displayed.');
  1489. // Verify that field and instance settings are correct.
  1490. $field_info = field_info_field($this->field_name);
  1491. $this->assertEqual(sizeof($field_info['settings']['allowed_values']), 1, 'Only one vocabulary is allowed for the field.');
  1492. // The widget should still be displayed.
  1493. $this->drupalGet('test-entity/add/test-bundle');
  1494. $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is still displayed.');
  1495. // Term 1 should still pass validation.
  1496. $edit = array(
  1497. "{$this->field_name}[$langcode][]" => array($term1->tid),
  1498. );
  1499. $this->drupalPost(NULL, $edit, t('Save'));
  1500. }
  1501. }
  1502. /**
  1503. * Test taxonomy token replacement in strings.
  1504. */
  1505. class TaxonomyTokenReplaceTestCase extends TaxonomyWebTestCase {
  1506. public static function getInfo() {
  1507. return array(
  1508. 'name' => 'Taxonomy token replacement',
  1509. 'description' => 'Generates text using placeholders for dummy content to check taxonomy token replacement.',
  1510. 'group' => 'Taxonomy',
  1511. );
  1512. }
  1513. function setUp() {
  1514. parent::setUp();
  1515. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
  1516. $this->drupalLogin($this->admin_user);
  1517. $this->vocabulary = $this->createVocabulary();
  1518. $this->langcode = LANGUAGE_NONE;
  1519. $field = array(
  1520. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  1521. 'type' => 'taxonomy_term_reference',
  1522. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1523. 'settings' => array(
  1524. 'allowed_values' => array(
  1525. array(
  1526. 'vocabulary' => $this->vocabulary->machine_name,
  1527. 'parent' => 0,
  1528. ),
  1529. ),
  1530. ),
  1531. );
  1532. field_create_field($field);
  1533. $this->instance = array(
  1534. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  1535. 'bundle' => 'article',
  1536. 'entity_type' => 'node',
  1537. 'widget' => array(
  1538. 'type' => 'options_select',
  1539. ),
  1540. 'display' => array(
  1541. 'default' => array(
  1542. 'type' => 'taxonomy_term_reference_link',
  1543. ),
  1544. ),
  1545. );
  1546. field_create_instance($this->instance);
  1547. }
  1548. /**
  1549. * Creates some terms and a node, then tests the tokens generated from them.
  1550. */
  1551. function testTaxonomyTokenReplacement() {
  1552. global $language;
  1553. // Create two taxonomy terms.
  1554. $term1 = $this->createTerm($this->vocabulary);
  1555. $term2 = $this->createTerm($this->vocabulary);
  1556. // Edit $term2, setting $term1 as parent.
  1557. $edit = array();
  1558. $edit['name'] = '<blink>Blinking Text</blink>';
  1559. $edit['parent[]'] = array($term1->tid);
  1560. $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));
  1561. // Create node with term2.
  1562. $edit = array();
  1563. $node = $this->drupalCreateNode(array('type' => 'article'));
  1564. $edit[$this->instance['field_name'] . '[' . $this->langcode . '][]'] = $term2->tid;
  1565. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1566. // Generate and test sanitized tokens for term1.
  1567. $tests = array();
  1568. $tests['[term:tid]'] = $term1->tid;
  1569. $tests['[term:name]'] = check_plain($term1->name);
  1570. $tests['[term:description]'] = check_markup($term1->description, $term1->format);
  1571. $tests['[term:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
  1572. $tests['[term:node-count]'] = 0;
  1573. $tests['[term:parent:name]'] = '[term:parent:name]';
  1574. $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
  1575. foreach ($tests as $input => $expected) {
  1576. $output = token_replace($input, array('term' => $term1), array('language' => $language));
  1577. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1578. }
  1579. // Generate and test sanitized tokens for term2.
  1580. $tests = array();
  1581. $tests['[term:tid]'] = $term2->tid;
  1582. $tests['[term:name]'] = check_plain($term2->name);
  1583. $tests['[term:description]'] = check_markup($term2->description, $term2->format);
  1584. $tests['[term:url]'] = url('taxonomy/term/' . $term2->tid, array('absolute' => TRUE));
  1585. $tests['[term:node-count]'] = 1;
  1586. $tests['[term:parent:name]'] = check_plain($term1->name);
  1587. $tests['[term:parent:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
  1588. $tests['[term:parent:parent:name]'] = '[term:parent:parent:name]';
  1589. $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
  1590. // Test to make sure that we generated something for each token.
  1591. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1592. foreach ($tests as $input => $expected) {
  1593. $output = token_replace($input, array('term' => $term2), array('language' => $language));
  1594. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1595. }
  1596. // Generate and test unsanitized tokens.
  1597. $tests['[term:name]'] = $term2->name;
  1598. $tests['[term:description]'] = $term2->description;
  1599. $tests['[term:parent:name]'] = $term1->name;
  1600. $tests['[term:vocabulary:name]'] = $this->vocabulary->name;
  1601. foreach ($tests as $input => $expected) {
  1602. $output = token_replace($input, array('term' => $term2), array('language' => $language, 'sanitize' => FALSE));
  1603. $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1604. }
  1605. // Generate and test sanitized tokens.
  1606. $tests = array();
  1607. $tests['[vocabulary:vid]'] = $this->vocabulary->vid;
  1608. $tests['[vocabulary:name]'] = check_plain($this->vocabulary->name);
  1609. $tests['[vocabulary:description]'] = filter_xss($this->vocabulary->description);
  1610. $tests['[vocabulary:node-count]'] = 1;
  1611. $tests['[vocabulary:term-count]'] = 2;
  1612. // Test to make sure that we generated something for each token.
  1613. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1614. foreach ($tests as $input => $expected) {
  1615. $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language));
  1616. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
  1617. }
  1618. // Generate and test unsanitized tokens.
  1619. $tests['[vocabulary:name]'] = $this->vocabulary->name;
  1620. $tests['[vocabulary:description]'] = $this->vocabulary->description;
  1621. foreach ($tests as $input => $expected) {
  1622. $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language, 'sanitize' => FALSE));
  1623. $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
  1624. }
  1625. }
  1626. }
  1627. /**
  1628. * Tests for verifying that taxonomy pages use the correct theme.
  1629. */
  1630. class TaxonomyThemeTestCase extends TaxonomyWebTestCase {
  1631. public static function getInfo() {
  1632. return array(
  1633. 'name' => 'Taxonomy theme switching',
  1634. 'description' => 'Verifies that various taxonomy pages use the expected theme.',
  1635. 'group' => 'Taxonomy',
  1636. );
  1637. }
  1638. function setUp() {
  1639. parent::setUp();
  1640. // Make sure we are using distinct default and administrative themes for
  1641. // the duration of these tests.
  1642. variable_set('theme_default', 'bartik');
  1643. variable_set('admin_theme', 'seven');
  1644. // Create and log in as a user who has permission to add and edit taxonomy
  1645. // terms and view the administrative theme.
  1646. $admin_user = $this->drupalCreateUser(array('administer taxonomy', 'view the administration theme'));
  1647. $this->drupalLogin($admin_user);
  1648. }
  1649. /**
  1650. * Test the theme used when adding, viewing and editing taxonomy terms.
  1651. */
  1652. function testTaxonomyTermThemes() {
  1653. // Adding a term to a vocabulary is considered an administrative action and
  1654. // should use the administrative theme.
  1655. $vocabulary = $this->createVocabulary();
  1656. $this->drupalGet('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add');
  1657. $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for adding a taxonomy term.");
  1658. // Viewing a taxonomy term should use the default theme.
  1659. $term = $this->createTerm($vocabulary);
  1660. $this->drupalGet('taxonomy/term/' . $term->tid);
  1661. $this->assertRaw('bartik/css/style.css', "The default theme's CSS appears on the page for viewing a taxonomy term.");
  1662. // Editing a taxonomy term should use the same theme as adding one.
  1663. $this->drupalGet('taxonomy/term/' . $term->tid . '/edit');
  1664. $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for editing a taxonomy term.");
  1665. }
  1666. }
  1667. /**
  1668. * Tests the functionality of EntityFieldQuery for taxonomy entities.
  1669. */
  1670. class TaxonomyEFQTestCase extends TaxonomyWebTestCase {
  1671. public static function getInfo() {
  1672. return array(
  1673. 'name' => 'Taxonomy EntityFieldQuery',
  1674. 'description' => 'Verifies operation of a taxonomy-based EntityFieldQuery.',
  1675. 'group' => 'Taxonomy',
  1676. );
  1677. }
  1678. function setUp() {
  1679. parent::setUp();
  1680. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
  1681. $this->drupalLogin($this->admin_user);
  1682. $this->vocabulary = $this->createVocabulary();
  1683. }
  1684. /**
  1685. * Tests that a basic taxonomy EntityFieldQuery works.
  1686. */
  1687. function testTaxonomyEFQ() {
  1688. $terms = array();
  1689. for ($i = 0; $i < 5; $i++) {
  1690. $term = $this->createTerm($this->vocabulary);
  1691. $terms[$term->tid] = $term;
  1692. }
  1693. $query = new EntityFieldQuery();
  1694. $query->entityCondition('entity_type', 'taxonomy_term');
  1695. $result = $query->execute();
  1696. $result = $result['taxonomy_term'];
  1697. asort($result);
  1698. $this->assertEqual(array_keys($terms), array_keys($result), 'Taxonomy terms were retrieved by EntityFieldQuery.');
  1699. // Create a second vocabulary and five more terms.
  1700. $vocabulary2 = $this->createVocabulary();
  1701. $terms2 = array();
  1702. for ($i = 0; $i < 5; $i++) {
  1703. $term = $this->createTerm($vocabulary2);
  1704. $terms2[$term->tid] = $term;
  1705. }
  1706. $query = new EntityFieldQuery();
  1707. $query->entityCondition('entity_type', 'taxonomy_term');
  1708. $query->entityCondition('bundle', $vocabulary2->machine_name);
  1709. $result = $query->execute();
  1710. $result = $result['taxonomy_term'];
  1711. asort($result);
  1712. $this->assertEqual(array_keys($terms2), array_keys($result), format_string('Taxonomy terms from the %name vocabulary were retrieved by EntityFieldQuery.', array('%name' => $vocabulary2->name)));
  1713. }
  1714. }