taxonomy.test 76 KB

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