taxonomy.test 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  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. // Test the autocomplete path without passing a field_name and terms.
  627. // This should not trigger a PHP notice.
  628. $field_name = '';
  629. $message = t("Taxonomy field @field_name not found.", array('@field_name' => $field_name));
  630. $this->drupalGet('taxonomy/autocomplete');
  631. $this->assertRaw($message, 'Autocomplete returns correct error message when no taxonomy field is given.');
  632. }
  633. /**
  634. * Tests term autocompletion edge cases with slashes in the names.
  635. */
  636. function testTermAutocompletion() {
  637. // Add a term with a slash in the name.
  638. $first_term = $this->createTerm($this->vocabulary);
  639. $first_term->name = '10/16/2011';
  640. taxonomy_term_save($first_term);
  641. // Add another term that differs after the slash character.
  642. $second_term = $this->createTerm($this->vocabulary);
  643. $second_term->name = '10/17/2011';
  644. taxonomy_term_save($second_term);
  645. // Add another term that has both a comma and a slash character.
  646. $third_term = $this->createTerm($this->vocabulary);
  647. $third_term->name = 'term with, a comma and / a slash';
  648. taxonomy_term_save($third_term);
  649. // Try to autocomplete a term name that matches both terms.
  650. // We should get both term in a json encoded string.
  651. $input = '10/';
  652. $path = 'taxonomy/autocomplete/taxonomy_';
  653. $path .= $this->vocabulary->machine_name . '/' . $input;
  654. // The result order is not guaranteed, so check each term separately.
  655. $url = url($path, array('absolute' => TRUE));
  656. $result = drupal_http_request($url);
  657. $data = drupal_json_decode($result->data);
  658. $this->assertEqual($data[$first_term->name], check_plain($first_term->name), 'Autocomplete returned the first matching term.');
  659. $this->assertEqual($data[$second_term->name], check_plain($second_term->name), 'Autocomplete returned the second matching term.');
  660. // Try to autocomplete a term name that matches first term.
  661. // We should only get the first term in a json encoded string.
  662. $input = '10/16';
  663. $url = 'taxonomy/autocomplete/taxonomy_';
  664. $url .= $this->vocabulary->machine_name . '/' . $input;
  665. $this->drupalGet($url);
  666. $target = array($first_term->name => check_plain($first_term->name));
  667. $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');
  668. // Try to autocomplete a term name with both a comma and a slash.
  669. $input = '"term with, comma and / a';
  670. $url = 'taxonomy/autocomplete/taxonomy_';
  671. $url .= $this->vocabulary->machine_name . '/' . $input;
  672. $this->drupalGet($url);
  673. $n = $third_term->name;
  674. // Term names containing commas or quotes must be wrapped in quotes.
  675. if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
  676. $n = '"' . str_replace('"', '""', $third_term->name) . '"';
  677. }
  678. $target = array($n => check_plain($third_term->name));
  679. $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
  680. }
  681. /**
  682. * Save, edit and delete a term using the user interface.
  683. */
  684. function testTermInterface() {
  685. $edit = array(
  686. 'name' => $this->randomName(12),
  687. 'description[value]' => $this->randomName(100),
  688. );
  689. // Explicitly set the parents field to 'root', to ensure that
  690. // taxonomy_form_term_submit() handles the invalid term ID correctly.
  691. $edit['parent[]'] = array(0);
  692. // Create the term to edit.
  693. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
  694. $terms = taxonomy_get_term_by_name($edit['name']);
  695. $term = reset($terms);
  696. $this->assertNotNull($term, 'Term found in database.');
  697. // Submitting a term takes us to the add page; we need the List page.
  698. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  699. // Test edit link as accessed from Taxonomy administration pages.
  700. // Because Simpletest creates its own database when running tests, we know
  701. // the first edit link found on the listing page is to our term.
  702. $this->clickLink(t('edit'));
  703. $this->assertRaw($edit['name'], 'The randomly generated term name is present.');
  704. $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
  705. $edit = array(
  706. 'name' => $this->randomName(14),
  707. 'description[value]' => $this->randomName(102),
  708. );
  709. // Edit the term.
  710. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
  711. // Check that the term is still present at admin UI after edit.
  712. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  713. $this->assertText($edit['name'], 'The randomly generated term name is present.');
  714. $this->assertLink(t('edit'));
  715. // View the term and check that it is correct.
  716. $this->drupalGet('taxonomy/term/' . $term->tid);
  717. $this->assertText($edit['name'], 'The randomly generated term name is present.');
  718. $this->assertText($edit['description[value]'], 'The randomly generated term description is present.');
  719. // Did this page request display a 'term-listing-heading'?
  720. $this->assertPattern('|class="taxonomy-term-description"|', 'Term page displayed the term description element.');
  721. // Check that it does NOT show a description when description is blank.
  722. $term->description = '';
  723. taxonomy_term_save($term);
  724. $this->drupalGet('taxonomy/term/' . $term->tid);
  725. $this->assertNoPattern('|class="taxonomy-term-description"|', 'Term page did not display the term description when description was blank.');
  726. // Check that the term feed page is working.
  727. $this->drupalGet('taxonomy/term/' . $term->tid . '/feed');
  728. // Check that the term edit page does not try to interpret additional path
  729. // components as arguments for taxonomy_form_term().
  730. $this->drupalGet('taxonomy/term/' . $term->tid . '/edit/' . $this->randomName());
  731. // Delete the term.
  732. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', array(), t('Delete'));
  733. $this->drupalPost(NULL, NULL, t('Delete'));
  734. // Assert that the term no longer exists.
  735. $this->drupalGet('taxonomy/term/' . $term->tid);
  736. $this->assertResponse(404, 'The taxonomy term page was not found.');
  737. }
  738. /**
  739. * Save, edit and delete a term using the user interface.
  740. */
  741. function testTermReorder() {
  742. $this->createTerm($this->vocabulary);
  743. $this->createTerm($this->vocabulary);
  744. $this->createTerm($this->vocabulary);
  745. // Fetch the created terms in the default alphabetical order, i.e. term1
  746. // precedes term2 alphabetically, and term2 precedes term3.
  747. drupal_static_reset('taxonomy_get_tree');
  748. drupal_static_reset('taxonomy_get_treeparent');
  749. drupal_static_reset('taxonomy_get_treeterms');
  750. list($term1, $term2, $term3) = taxonomy_get_tree($this->vocabulary->vid);
  751. $this->drupalGet('admin/structure/taxonomy/' . $this->vocabulary->machine_name);
  752. // Each term has four hidden fields, "tid:1:0[tid]", "tid:1:0[parent]",
  753. // "tid:1:0[depth]", and "tid:1:0[weight]". Change the order to term2,
  754. // term3, term1 by setting weight property, make term3 a child of term2 by
  755. // setting the parent and depth properties, and update all hidden fields.
  756. $edit = array(
  757. 'tid:' . $term2->tid . ':0[tid]' => $term2->tid,
  758. 'tid:' . $term2->tid . ':0[parent]' => 0,
  759. 'tid:' . $term2->tid . ':0[depth]' => 0,
  760. 'tid:' . $term2->tid . ':0[weight]' => 0,
  761. 'tid:' . $term3->tid . ':0[tid]' => $term3->tid,
  762. 'tid:' . $term3->tid . ':0[parent]' => $term2->tid,
  763. 'tid:' . $term3->tid . ':0[depth]' => 1,
  764. 'tid:' . $term3->tid . ':0[weight]' => 1,
  765. 'tid:' . $term1->tid . ':0[tid]' => $term1->tid,
  766. 'tid:' . $term1->tid . ':0[parent]' => 0,
  767. 'tid:' . $term1->tid . ':0[depth]' => 0,
  768. 'tid:' . $term1->tid . ':0[weight]' => 2,
  769. );
  770. $this->drupalPost(NULL, $edit, t('Save'));
  771. drupal_static_reset('taxonomy_get_tree');
  772. drupal_static_reset('taxonomy_get_treeparent');
  773. drupal_static_reset('taxonomy_get_treeterms');
  774. $terms = taxonomy_get_tree($this->vocabulary->vid);
  775. $this->assertEqual($terms[0]->tid, $term2->tid, 'Term 2 was moved above term 1.');
  776. $this->assertEqual($terms[1]->parents, array($term2->tid), 'Term 3 was made a child of term 2.');
  777. $this->assertEqual($terms[2]->tid, $term1->tid, 'Term 1 was moved below term 2.');
  778. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name, array(), t('Reset to alphabetical'));
  779. // Submit confirmation form.
  780. $this->drupalPost(NULL, array(), t('Reset to alphabetical'));
  781. drupal_static_reset('taxonomy_get_tree');
  782. drupal_static_reset('taxonomy_get_treeparent');
  783. drupal_static_reset('taxonomy_get_treeterms');
  784. $terms = taxonomy_get_tree($this->vocabulary->vid);
  785. $this->assertEqual($terms[0]->tid, $term1->tid, 'Term 1 was moved to back above term 2.');
  786. $this->assertEqual($terms[1]->tid, $term2->tid, 'Term 2 was moved to back below term 1.');
  787. $this->assertEqual($terms[2]->tid, $term3->tid, 'Term 3 is still below term 2.');
  788. $this->assertEqual($terms[2]->parents, array($term2->tid), 'Term 3 is still a child of term 2.' . var_export($terms[1]->tid, 1));
  789. }
  790. /**
  791. * Test saving a term with multiple parents through the UI.
  792. */
  793. function testTermMultipleParentsInterface() {
  794. // Add a new term to the vocabulary so that we can have multiple parents.
  795. $parent = $this->createTerm($this->vocabulary);
  796. // Add a new term with multiple parents.
  797. $edit = array(
  798. 'name' => $this->randomName(12),
  799. 'description[value]' => $this->randomName(100),
  800. 'parent[]' => array(0, $parent->tid),
  801. );
  802. // Save the new term.
  803. $this->drupalPost('admin/structure/taxonomy/' . $this->vocabulary->machine_name . '/add', $edit, t('Save'));
  804. // Check that the term was successfully created.
  805. $terms = taxonomy_get_term_by_name($edit['name']);
  806. $term = reset($terms);
  807. $this->assertNotNull($term, 'Term found in database.');
  808. $this->assertEqual($edit['name'], $term->name, 'Term name was successfully saved.');
  809. $this->assertEqual($edit['description[value]'], $term->description, 'Term description was successfully saved.');
  810. // Check that the parent tid is still there. The other parent (<root>) is
  811. // not added by taxonomy_get_parents().
  812. $parents = taxonomy_get_parents($term->tid);
  813. $parent = reset($parents);
  814. $this->assertEqual($edit['parent[]'][1], $parent->tid, 'Term parents were successfully saved.');
  815. }
  816. /**
  817. * Test taxonomy_get_term_by_name().
  818. */
  819. function testTaxonomyGetTermByName() {
  820. $term = $this->createTerm($this->vocabulary);
  821. // Load the term with the exact name.
  822. $terms = taxonomy_get_term_by_name($term->name);
  823. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name.');
  824. // Load the term with space concatenated.
  825. $terms = taxonomy_get_term_by_name(' ' . $term->name . ' ');
  826. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with extra whitespace.');
  827. // Load the term with name uppercased.
  828. $terms = taxonomy_get_term_by_name(strtoupper($term->name));
  829. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with uppercased name.');
  830. // Load the term with name lowercased.
  831. $terms = taxonomy_get_term_by_name(strtolower($term->name));
  832. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded with lowercased name.');
  833. // Try to load an invalid term name.
  834. $terms = taxonomy_get_term_by_name('Banana');
  835. $this->assertFalse($terms);
  836. // Try to load the term using a substring of the name.
  837. $terms = taxonomy_get_term_by_name(drupal_substr($term->name, 2));
  838. $this->assertFalse($terms);
  839. // Create a new term in a different vocabulary with the same name.
  840. $new_vocabulary = $this->createVocabulary();
  841. $new_term = new stdClass();
  842. $new_term->name = $term->name;
  843. $new_term->vid = $new_vocabulary->vid;
  844. taxonomy_term_save($new_term);
  845. // Load multiple terms with the same name.
  846. $terms = taxonomy_get_term_by_name($term->name);
  847. $this->assertEqual(count($terms), 2, 'Two terms loaded with the same name.');
  848. // Load single term when restricted to one vocabulary.
  849. $terms = taxonomy_get_term_by_name($term->name, $this->vocabulary->machine_name);
  850. $this->assertEqual(count($terms), 1, 'One term loaded when restricted by vocabulary.');
  851. $this->assertTrue(isset($terms[$term->tid]), 'Term loaded using exact name and vocabulary machine name.');
  852. // Create a new term with another name.
  853. $term2 = $this->createTerm($this->vocabulary);
  854. // Try to load a term by name that doesn't exist in this vocabulary but
  855. // exists in another vocabulary.
  856. $terms = taxonomy_get_term_by_name($term2->name, $new_vocabulary->machine_name);
  857. $this->assertFalse($terms, 'Invalid term name restricted by vocabulary machine name not loaded.');
  858. // Try to load terms filtering by a non-existing vocabulary.
  859. $terms = taxonomy_get_term_by_name($term2->name, 'non_existing_vocabulary');
  860. $this->assertEqual(count($terms), 0, 'No terms loaded when restricted by a non-existing vocabulary.');
  861. }
  862. }
  863. /**
  864. * Tests the rendering of term reference fields in RSS feeds.
  865. */
  866. class TaxonomyRSSTestCase extends TaxonomyWebTestCase {
  867. public static function getInfo() {
  868. return array(
  869. 'name' => 'Taxonomy RSS Content.',
  870. 'description' => 'Ensure that data added as terms appears in RSS feeds if "RSS Category" format is selected.',
  871. 'group' => 'Taxonomy',
  872. );
  873. }
  874. function setUp() {
  875. parent::setUp('taxonomy');
  876. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access', 'administer content types'));
  877. $this->drupalLogin($this->admin_user);
  878. $this->vocabulary = $this->createVocabulary();
  879. $field = array(
  880. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  881. 'type' => 'taxonomy_term_reference',
  882. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  883. 'settings' => array(
  884. 'allowed_values' => array(
  885. array(
  886. 'vocabulary' => $this->vocabulary->machine_name,
  887. 'parent' => 0,
  888. ),
  889. ),
  890. ),
  891. );
  892. field_create_field($field);
  893. $this->instance = array(
  894. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  895. 'bundle' => 'article',
  896. 'entity_type' => 'node',
  897. 'widget' => array(
  898. 'type' => 'options_select',
  899. ),
  900. 'display' => array(
  901. 'default' => array(
  902. 'type' => 'taxonomy_term_reference_link',
  903. ),
  904. ),
  905. );
  906. field_create_instance($this->instance);
  907. }
  908. /**
  909. * Tests that terms added to nodes are displayed in core RSS feed.
  910. *
  911. * Create a node and assert that taxonomy terms appear in rss.xml.
  912. */
  913. function testTaxonomyRSS() {
  914. // Create two taxonomy terms.
  915. $term1 = $this->createTerm($this->vocabulary);
  916. // RSS display must be added manually.
  917. $this->drupalGet("admin/structure/types/manage/article/display");
  918. $edit = array(
  919. "view_modes_custom[rss]" => '1',
  920. );
  921. $this->drupalPost(NULL, $edit, t('Save'));
  922. // Change the format to 'RSS category'.
  923. $this->drupalGet("admin/structure/types/manage/article/display/rss");
  924. $edit = array(
  925. "fields[taxonomy_" . $this->vocabulary->machine_name . "][type]" => 'taxonomy_term_reference_rss_category',
  926. );
  927. $this->drupalPost(NULL, $edit, t('Save'));
  928. // Post an article.
  929. $edit = array();
  930. $langcode = LANGUAGE_NONE;
  931. $edit["title"] = $this->randomName();
  932. $edit[$this->instance['field_name'] . '[' . $langcode . '][]'] = $term1->tid;
  933. $this->drupalPost('node/add/article', $edit, t('Save'));
  934. // Check that the term is displayed when the RSS feed is viewed.
  935. $this->drupalGet('rss.xml');
  936. $test_element = array(
  937. 'key' => 'category',
  938. 'value' => $term1->name,
  939. 'attributes' => array(
  940. 'domain' => url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE)),
  941. ),
  942. );
  943. $this->assertRaw(format_xml_elements(array($test_element)), 'Term is displayed when viewing the rss feed.');
  944. }
  945. }
  946. /**
  947. * Tests the hook implementations that maintain the taxonomy index.
  948. */
  949. class TaxonomyTermIndexTestCase extends TaxonomyWebTestCase {
  950. public static function getInfo() {
  951. return array(
  952. 'name' => 'Taxonomy term index',
  953. 'description' => 'Tests the hook implementations that maintain the taxonomy index.',
  954. 'group' => 'Taxonomy',
  955. );
  956. }
  957. function setUp() {
  958. parent::setUp('taxonomy');
  959. // Create an administrative user.
  960. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
  961. $this->drupalLogin($this->admin_user);
  962. // Create a vocabulary and add two term reference fields to article nodes.
  963. $this->vocabulary = $this->createVocabulary();
  964. $this->field_name_1 = drupal_strtolower($this->randomName());
  965. $this->field_1 = array(
  966. 'field_name' => $this->field_name_1,
  967. 'type' => 'taxonomy_term_reference',
  968. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  969. 'settings' => array(
  970. 'allowed_values' => array(
  971. array(
  972. 'vocabulary' => $this->vocabulary->machine_name,
  973. 'parent' => 0,
  974. ),
  975. ),
  976. ),
  977. );
  978. field_create_field($this->field_1);
  979. $this->instance_1 = array(
  980. 'field_name' => $this->field_name_1,
  981. 'bundle' => 'article',
  982. 'entity_type' => 'node',
  983. 'widget' => array(
  984. 'type' => 'options_select',
  985. ),
  986. 'display' => array(
  987. 'default' => array(
  988. 'type' => 'taxonomy_term_reference_link',
  989. ),
  990. ),
  991. );
  992. field_create_instance($this->instance_1);
  993. $this->field_name_2 = drupal_strtolower($this->randomName());
  994. $this->field_2 = array(
  995. 'field_name' => $this->field_name_2,
  996. 'type' => 'taxonomy_term_reference',
  997. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  998. 'settings' => array(
  999. 'allowed_values' => array(
  1000. array(
  1001. 'vocabulary' => $this->vocabulary->machine_name,
  1002. 'parent' => 0,
  1003. ),
  1004. ),
  1005. ),
  1006. );
  1007. field_create_field($this->field_2);
  1008. $this->instance_2 = array(
  1009. 'field_name' => $this->field_name_2,
  1010. 'bundle' => 'article',
  1011. 'entity_type' => 'node',
  1012. 'widget' => array(
  1013. 'type' => 'options_select',
  1014. ),
  1015. 'display' => array(
  1016. 'default' => array(
  1017. 'type' => 'taxonomy_term_reference_link',
  1018. ),
  1019. ),
  1020. );
  1021. field_create_instance($this->instance_2);
  1022. }
  1023. /**
  1024. * Tests that the taxonomy index is maintained properly.
  1025. */
  1026. function testTaxonomyIndex() {
  1027. // Create terms in the vocabulary.
  1028. $term_1 = $this->createTerm($this->vocabulary);
  1029. $term_2 = $this->createTerm($this->vocabulary);
  1030. // Post an article.
  1031. $edit = array();
  1032. $langcode = LANGUAGE_NONE;
  1033. $edit["title"] = $this->randomName();
  1034. $edit["body[$langcode][0][value]"] = $this->randomName();
  1035. $edit["{$this->field_name_1}[$langcode][]"] = $term_1->tid;
  1036. $edit["{$this->field_name_2}[$langcode][]"] = $term_1->tid;
  1037. $this->drupalPost('node/add/article', $edit, t('Save'));
  1038. // Check that the term is indexed, and only once.
  1039. $node = $this->drupalGetNodeByTitle($edit["title"]);
  1040. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1041. ':nid' => $node->nid,
  1042. ':tid' => $term_1->tid,
  1043. ))->fetchField();
  1044. $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
  1045. // Update the article to change one term.
  1046. $edit["{$this->field_name_1}[$langcode][]"] = $term_2->tid;
  1047. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1048. // Check that both terms are indexed.
  1049. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1050. ':nid' => $node->nid,
  1051. ':tid' => $term_1->tid,
  1052. ))->fetchField();
  1053. $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
  1054. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1055. ':nid' => $node->nid,
  1056. ':tid' => $term_2->tid,
  1057. ))->fetchField();
  1058. $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
  1059. // Update the article to change another term.
  1060. $edit["{$this->field_name_2}[$langcode][]"] = $term_2->tid;
  1061. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1062. // Check that only one term is indexed.
  1063. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1064. ':nid' => $node->nid,
  1065. ':tid' => $term_1->tid,
  1066. ))->fetchField();
  1067. $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
  1068. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1069. ':nid' => $node->nid,
  1070. ':tid' => $term_2->tid,
  1071. ))->fetchField();
  1072. $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
  1073. // Redo the above tests without interface.
  1074. $update_node = array(
  1075. 'nid' => $node->nid,
  1076. 'vid' => $node->vid,
  1077. 'uid' => $node->uid,
  1078. 'type' => $node->type,
  1079. 'title' => $this->randomName(),
  1080. );
  1081. // Update the article with no term changed.
  1082. $updated_node = (object) $update_node;
  1083. node_save($updated_node);
  1084. // Check that the index was not changed.
  1085. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1086. ':nid' => $node->nid,
  1087. ':tid' => $term_1->tid,
  1088. ))->fetchField();
  1089. $this->assertEqual(0, $index_count, 'Term 1 is not indexed.');
  1090. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1091. ':nid' => $node->nid,
  1092. ':tid' => $term_2->tid,
  1093. ))->fetchField();
  1094. $this->assertEqual(1, $index_count, 'Term 2 is indexed once.');
  1095. // Update the article to change one term.
  1096. $update_node[$this->field_name_1][$langcode] = array(array('tid' => $term_1->tid));
  1097. $updated_node = (object) $update_node;
  1098. node_save($updated_node);
  1099. // Check that both terms are indexed.
  1100. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1101. ':nid' => $node->nid,
  1102. ':tid' => $term_1->tid,
  1103. ))->fetchField();
  1104. $this->assertEqual(1, $index_count, 'Term 1 is indexed.');
  1105. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1106. ':nid' => $node->nid,
  1107. ':tid' => $term_2->tid,
  1108. ))->fetchField();
  1109. $this->assertEqual(1, $index_count, 'Term 2 is indexed.');
  1110. // Update the article to change another term.
  1111. $update_node[$this->field_name_2][$langcode] = array(array('tid' => $term_1->tid));
  1112. $updated_node = (object) $update_node;
  1113. node_save($updated_node);
  1114. // Check that only one term is indexed.
  1115. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1116. ':nid' => $node->nid,
  1117. ':tid' => $term_1->tid,
  1118. ))->fetchField();
  1119. $this->assertEqual(1, $index_count, 'Term 1 is indexed once.');
  1120. $index_count = db_query('SELECT COUNT(*) FROM {taxonomy_index} WHERE nid = :nid AND tid = :tid', array(
  1121. ':nid' => $node->nid,
  1122. ':tid' => $term_2->tid,
  1123. ))->fetchField();
  1124. $this->assertEqual(0, $index_count, 'Term 2 is not indexed.');
  1125. }
  1126. /**
  1127. * Tests that there is a link to the parent term on the child term page.
  1128. */
  1129. function testTaxonomyTermHierarchyBreadcrumbs() {
  1130. // Create two taxonomy terms and set term2 as the parent of term1.
  1131. $term1 = $this->createTerm($this->vocabulary);
  1132. $term2 = $this->createTerm($this->vocabulary);
  1133. $term1->parent = array($term2->tid);
  1134. taxonomy_term_save($term1);
  1135. // Verify that the page breadcrumbs include a link to the parent term.
  1136. $this->drupalGet('taxonomy/term/' . $term1->tid);
  1137. $this->assertRaw(l($term2->name, 'taxonomy/term/' . $term2->tid), 'Parent term link is displayed when viewing the node.');
  1138. }
  1139. }
  1140. /**
  1141. * Test the taxonomy_term_load_multiple() function.
  1142. */
  1143. class TaxonomyLoadMultipleTestCase extends TaxonomyWebTestCase {
  1144. public static function getInfo() {
  1145. return array(
  1146. 'name' => 'Taxonomy term multiple loading',
  1147. 'description' => 'Test the loading of multiple taxonomy terms at once',
  1148. 'group' => 'Taxonomy',
  1149. );
  1150. }
  1151. function setUp() {
  1152. parent::setUp();
  1153. $this->taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
  1154. $this->drupalLogin($this->taxonomy_admin);
  1155. }
  1156. /**
  1157. * Create a vocabulary and some taxonomy terms, ensuring they're loaded
  1158. * correctly using taxonomy_term_load_multiple().
  1159. */
  1160. function testTaxonomyTermMultipleLoad() {
  1161. // Create a vocabulary.
  1162. $vocabulary = $this->createVocabulary();
  1163. // Create five terms in the vocabulary.
  1164. $i = 0;
  1165. while ($i < 5) {
  1166. $i++;
  1167. $this->createTerm($vocabulary);
  1168. }
  1169. // Load the terms from the vocabulary.
  1170. $terms = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
  1171. $count = count($terms);
  1172. $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. !count terms.', array('!count' => $count)));
  1173. // Load the same terms again by tid.
  1174. $terms2 = taxonomy_term_load_multiple(array_keys($terms));
  1175. $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.');
  1176. $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.');
  1177. // Load the terms by tid, with a condition on vid.
  1178. $terms3 = taxonomy_term_load_multiple(array_keys($terms2), array('vid' => $vocabulary->vid));
  1179. $this->assertEqual($terms2, $terms3);
  1180. // Remove one term from the array, then delete it.
  1181. $deleted = array_shift($terms3);
  1182. taxonomy_term_delete($deleted->tid);
  1183. $deleted_term = taxonomy_term_load($deleted->tid);
  1184. $this->assertFalse($deleted_term);
  1185. // Load terms from the vocabulary by vid.
  1186. $terms4 = taxonomy_term_load_multiple(NULL, array('vid' => $vocabulary->vid));
  1187. $this->assertEqual(count($terms4), 4, 'Correct number of terms were loaded.');
  1188. $this->assertFalse(isset($terms4[$deleted->tid]));
  1189. // Create a single term and load it by name.
  1190. $term = $this->createTerm($vocabulary);
  1191. $loaded_terms = taxonomy_term_load_multiple(array(), array('name' => $term->name));
  1192. $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.');
  1193. $loaded_term = reset($loaded_terms);
  1194. $this->assertEqual($term->tid, $loaded_term->tid, 'Term loaded by name successfully.');
  1195. }
  1196. }
  1197. /**
  1198. * Tests for taxonomy hook invocation.
  1199. */
  1200. class TaxonomyHooksTestCase extends TaxonomyWebTestCase {
  1201. public static function getInfo() {
  1202. return array(
  1203. 'name' => 'Taxonomy term hooks',
  1204. 'description' => 'Hooks for taxonomy term load/save/delete.',
  1205. 'group' => 'Taxonomy',
  1206. );
  1207. }
  1208. function setUp() {
  1209. parent::setUp('taxonomy', 'taxonomy_test');
  1210. module_load_include('inc', 'taxonomy', 'taxonomy.pages');
  1211. $taxonomy_admin = $this->drupalCreateUser(array('administer taxonomy'));
  1212. $this->drupalLogin($taxonomy_admin);
  1213. }
  1214. /**
  1215. * Test that hooks are run correctly on creating, editing, viewing,
  1216. * and deleting a term.
  1217. *
  1218. * @see taxonomy_test.module
  1219. */
  1220. function testTaxonomyTermHooks() {
  1221. $vocabulary = $this->createVocabulary();
  1222. // Create a term with one antonym.
  1223. $edit = array(
  1224. 'name' => $this->randomName(),
  1225. 'antonym' => 'Long',
  1226. );
  1227. $this->drupalPost('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add', $edit, t('Save'));
  1228. $terms = taxonomy_get_term_by_name($edit['name']);
  1229. $term = reset($terms);
  1230. $this->assertEqual($term->antonym, $edit['antonym'], 'Antonym was loaded into the term object.');
  1231. // Update the term with a different antonym.
  1232. $edit = array(
  1233. 'name' => $this->randomName(),
  1234. 'antonym' => 'Short',
  1235. );
  1236. $this->drupalPost('taxonomy/term/' . $term->tid . '/edit', $edit, t('Save'));
  1237. taxonomy_terms_static_reset();
  1238. $term = taxonomy_term_load($term->tid);
  1239. $this->assertEqual($edit['antonym'], $term->antonym, 'Antonym was successfully edited.');
  1240. // View the term and ensure that hook_taxonomy_term_view() and
  1241. // hook_entity_view() are invoked.
  1242. $term = taxonomy_term_load($term->tid);
  1243. $term_build = taxonomy_term_page($term);
  1244. $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_term_view_check']), 'hook_taxonomy_term_view() was invoked when viewing the term.');
  1245. $this->assertFalse(empty($term_build['term_heading']['term']['taxonomy_test_entity_view_check']), 'hook_entity_view() was invoked when viewing the term.');
  1246. // Delete the term.
  1247. taxonomy_term_delete($term->tid);
  1248. $antonym = db_query('SELECT tid FROM {taxonomy_term_antonym} WHERE tid = :tid', array(':tid' => $term->tid))->fetchField();
  1249. $this->assertFalse($antonym, 'The antonym were deleted from the database.');
  1250. }
  1251. }
  1252. /**
  1253. * Tests for taxonomy term field and formatter.
  1254. */
  1255. class TaxonomyTermFieldTestCase extends TaxonomyWebTestCase {
  1256. protected $instance;
  1257. protected $vocabulary;
  1258. public static function getInfo() {
  1259. return array(
  1260. 'name' => 'Taxonomy term reference field',
  1261. 'description' => 'Test the creation of term fields.',
  1262. 'group' => 'Taxonomy',
  1263. );
  1264. }
  1265. function setUp() {
  1266. parent::setUp('field_test');
  1267. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
  1268. $this->drupalLogin($web_user);
  1269. $this->vocabulary = $this->createVocabulary();
  1270. // Setup a field and instance.
  1271. $this->field_name = drupal_strtolower($this->randomName());
  1272. $this->field = array(
  1273. 'field_name' => $this->field_name,
  1274. 'type' => 'taxonomy_term_reference',
  1275. 'settings' => array(
  1276. 'allowed_values' => array(
  1277. array(
  1278. 'vocabulary' => $this->vocabulary->machine_name,
  1279. 'parent' => '0',
  1280. ),
  1281. ),
  1282. )
  1283. );
  1284. field_create_field($this->field);
  1285. $this->instance = array(
  1286. 'field_name' => $this->field_name,
  1287. 'entity_type' => 'test_entity',
  1288. 'bundle' => 'test_bundle',
  1289. 'widget' => array(
  1290. 'type' => 'options_select',
  1291. ),
  1292. 'display' => array(
  1293. 'full' => array(
  1294. 'type' => 'taxonomy_term_reference_link',
  1295. ),
  1296. ),
  1297. );
  1298. field_create_instance($this->instance);
  1299. }
  1300. /**
  1301. * Test term field validation.
  1302. */
  1303. function testTaxonomyTermFieldValidation() {
  1304. // Test valid and invalid values with field_attach_validate().
  1305. $langcode = LANGUAGE_NONE;
  1306. $entity = field_test_create_stub_entity();
  1307. $term = $this->createTerm($this->vocabulary);
  1308. $entity->{$this->field_name}[$langcode][0]['tid'] = $term->tid;
  1309. try {
  1310. field_attach_validate('test_entity', $entity);
  1311. $this->pass('Correct term does not cause validation error.');
  1312. }
  1313. catch (FieldValidationException $e) {
  1314. $this->fail('Correct term does not cause validation error.');
  1315. }
  1316. $entity = field_test_create_stub_entity();
  1317. $bad_term = $this->createTerm($this->createVocabulary());
  1318. $entity->{$this->field_name}[$langcode][0]['tid'] = $bad_term->tid;
  1319. try {
  1320. field_attach_validate('test_entity', $entity);
  1321. $this->fail('Wrong term causes validation error.');
  1322. }
  1323. catch (FieldValidationException $e) {
  1324. $this->pass('Wrong term causes validation error.');
  1325. }
  1326. }
  1327. /**
  1328. * Test widgets.
  1329. */
  1330. function testTaxonomyTermFieldWidgets() {
  1331. // Create a term in the vocabulary.
  1332. $term = $this->createTerm($this->vocabulary);
  1333. // Display creation form.
  1334. $langcode = LANGUAGE_NONE;
  1335. $this->drupalGet('test-entity/add/test-bundle');
  1336. $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');
  1337. // Submit with some value.
  1338. $edit = array(
  1339. "{$this->field_name}[$langcode]" => array($term->tid),
  1340. );
  1341. $this->drupalPost(NULL, $edit, t('Save'));
  1342. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1343. $id = $match[1];
  1344. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
  1345. // Display the object.
  1346. $entity = field_test_entity_test_load($id);
  1347. $entities = array($id => $entity);
  1348. field_attach_prepare_view('test_entity', $entities, 'full');
  1349. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1350. $this->content = drupal_render($entity->content);
  1351. $this->assertText($term->name, 'Term name is displayed.');
  1352. // Delete the vocabulary and verify that the widget is gone.
  1353. taxonomy_vocabulary_delete($this->vocabulary->vid);
  1354. $this->drupalGet('test-entity/add/test-bundle');
  1355. $this->assertNoFieldByName("{$this->field_name}[$langcode]", '', 'Widget is not displayed.');
  1356. }
  1357. /**
  1358. * Tests that vocabulary machine name changes are mirrored in field definitions.
  1359. */
  1360. function testTaxonomyTermFieldChangeMachineName() {
  1361. // Add several entries in the 'allowed_values' setting, to make sure that
  1362. // they all get updated.
  1363. $this->field['settings']['allowed_values'] = array(
  1364. array(
  1365. 'vocabulary' => $this->vocabulary->machine_name,
  1366. 'parent' => '0',
  1367. ),
  1368. array(
  1369. 'vocabulary' => $this->vocabulary->machine_name,
  1370. 'parent' => '0',
  1371. ),
  1372. array(
  1373. 'vocabulary' => 'foo',
  1374. 'parent' => '0',
  1375. ),
  1376. );
  1377. field_update_field($this->field);
  1378. // Change the machine name.
  1379. $old_name = $this->vocabulary->machine_name;
  1380. $new_name = drupal_strtolower($this->randomName());
  1381. $this->vocabulary->machine_name = $new_name;
  1382. taxonomy_vocabulary_save($this->vocabulary);
  1383. // Check that entity bundles are properly updated.
  1384. $info = entity_get_info('taxonomy_term');
  1385. $this->assertFalse(isset($info['bundles'][$old_name]), 'The old bundle name does not appear in entity_get_info().');
  1386. $this->assertTrue(isset($info['bundles'][$new_name]), 'The new bundle name appears in entity_get_info().');
  1387. // Check that the field instance is still attached to the vocabulary.
  1388. $field = field_info_field($this->field_name);
  1389. $allowed_values = $field['settings']['allowed_values'];
  1390. $this->assertEqual($allowed_values[0]['vocabulary'], $new_name, 'Index 0: Machine name was updated correctly.');
  1391. $this->assertEqual($allowed_values[1]['vocabulary'], $new_name, 'Index 1: Machine name was updated correctly.');
  1392. $this->assertEqual($allowed_values[2]['vocabulary'], 'foo', 'Index 2: Machine name was left untouched.');
  1393. }
  1394. }
  1395. /**
  1396. * Tests a taxonomy term reference field that allows multiple vocabularies.
  1397. */
  1398. class TaxonomyTermFieldMultipleVocabularyTestCase extends TaxonomyWebTestCase {
  1399. protected $instance;
  1400. protected $vocabulary1;
  1401. protected $vocabulary2;
  1402. public static function getInfo() {
  1403. return array(
  1404. 'name' => 'Multiple vocabulary term reference field',
  1405. 'description' => 'Tests term reference fields that allow multiple vocabularies.',
  1406. 'group' => 'Taxonomy',
  1407. );
  1408. }
  1409. function setUp() {
  1410. parent::setUp('field_test');
  1411. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content', 'administer taxonomy'));
  1412. $this->drupalLogin($web_user);
  1413. $this->vocabulary1 = $this->createVocabulary();
  1414. $this->vocabulary2 = $this->createVocabulary();
  1415. // Set up a field and instance.
  1416. $this->field_name = drupal_strtolower($this->randomName());
  1417. $this->field = array(
  1418. 'field_name' => $this->field_name,
  1419. 'type' => 'taxonomy_term_reference',
  1420. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1421. 'settings' => array(
  1422. 'allowed_values' => array(
  1423. array(
  1424. 'vocabulary' => $this->vocabulary1->machine_name,
  1425. 'parent' => '0',
  1426. ),
  1427. array(
  1428. 'vocabulary' => $this->vocabulary2->machine_name,
  1429. 'parent' => '0',
  1430. ),
  1431. ),
  1432. )
  1433. );
  1434. field_create_field($this->field);
  1435. $this->instance = array(
  1436. 'field_name' => $this->field_name,
  1437. 'entity_type' => 'test_entity',
  1438. 'bundle' => 'test_bundle',
  1439. 'widget' => array(
  1440. 'type' => 'options_select',
  1441. ),
  1442. 'display' => array(
  1443. 'full' => array(
  1444. 'type' => 'taxonomy_term_reference_link',
  1445. ),
  1446. ),
  1447. );
  1448. field_create_instance($this->instance);
  1449. }
  1450. /**
  1451. * Tests term reference field and widget with multiple vocabularies.
  1452. */
  1453. function testTaxonomyTermFieldMultipleVocabularies() {
  1454. // Create a term in each vocabulary.
  1455. $term1 = $this->createTerm($this->vocabulary1);
  1456. $term2 = $this->createTerm($this->vocabulary2);
  1457. // Submit an entity with both terms.
  1458. $langcode = LANGUAGE_NONE;
  1459. $this->drupalGet('test-entity/add/test-bundle');
  1460. $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is displayed.');
  1461. $edit = array(
  1462. "{$this->field_name}[$langcode][]" => array($term1->tid, $term2->tid),
  1463. );
  1464. $this->drupalPost(NULL, $edit, t('Save'));
  1465. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1466. $id = $match[1];
  1467. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created.');
  1468. // Render the entity.
  1469. $entity = field_test_entity_test_load($id);
  1470. $entities = array($id => $entity);
  1471. field_attach_prepare_view('test_entity', $entities, 'full');
  1472. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1473. $this->content = drupal_render($entity->content);
  1474. $this->assertText($term1->name, 'Term 1 name is displayed.');
  1475. $this->assertText($term2->name, 'Term 2 name is displayed.');
  1476. // Delete vocabulary 2.
  1477. taxonomy_vocabulary_delete($this->vocabulary2->vid);
  1478. // Re-render the content.
  1479. $entity = field_test_entity_test_load($id);
  1480. $entities = array($id => $entity);
  1481. field_attach_prepare_view('test_entity', $entities, 'full');
  1482. $entity->content = field_attach_view('test_entity', $entity, 'full');
  1483. $this->plainTextContent = FALSE;
  1484. $this->content = drupal_render($entity->content);
  1485. // Term 1 should still be displayed; term 2 should not be.
  1486. $this->assertText($term1->name, 'Term 1 name is displayed.');
  1487. $this->assertNoText($term2->name, 'Term 2 name is not displayed.');
  1488. // Verify that field and instance settings are correct.
  1489. $field_info = field_info_field($this->field_name);
  1490. $this->assertEqual(sizeof($field_info['settings']['allowed_values']), 1, 'Only one vocabulary is allowed for the field.');
  1491. // The widget should still be displayed.
  1492. $this->drupalGet('test-entity/add/test-bundle');
  1493. $this->assertFieldByName("{$this->field_name}[$langcode][]", '', 'Widget is still displayed.');
  1494. // Term 1 should still pass validation.
  1495. $edit = array(
  1496. "{$this->field_name}[$langcode][]" => array($term1->tid),
  1497. );
  1498. $this->drupalPost(NULL, $edit, t('Save'));
  1499. }
  1500. }
  1501. /**
  1502. * Test taxonomy token replacement in strings.
  1503. */
  1504. class TaxonomyTokenReplaceTestCase extends TaxonomyWebTestCase {
  1505. public static function getInfo() {
  1506. return array(
  1507. 'name' => 'Taxonomy token replacement',
  1508. 'description' => 'Generates text using placeholders for dummy content to check taxonomy token replacement.',
  1509. 'group' => 'Taxonomy',
  1510. );
  1511. }
  1512. function setUp() {
  1513. parent::setUp();
  1514. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
  1515. $this->drupalLogin($this->admin_user);
  1516. $this->vocabulary = $this->createVocabulary();
  1517. $this->langcode = LANGUAGE_NONE;
  1518. $field = array(
  1519. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  1520. 'type' => 'taxonomy_term_reference',
  1521. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  1522. 'settings' => array(
  1523. 'allowed_values' => array(
  1524. array(
  1525. 'vocabulary' => $this->vocabulary->machine_name,
  1526. 'parent' => 0,
  1527. ),
  1528. ),
  1529. ),
  1530. );
  1531. field_create_field($field);
  1532. $this->instance = array(
  1533. 'field_name' => 'taxonomy_' . $this->vocabulary->machine_name,
  1534. 'bundle' => 'article',
  1535. 'entity_type' => 'node',
  1536. 'widget' => array(
  1537. 'type' => 'options_select',
  1538. ),
  1539. 'display' => array(
  1540. 'default' => array(
  1541. 'type' => 'taxonomy_term_reference_link',
  1542. ),
  1543. ),
  1544. );
  1545. field_create_instance($this->instance);
  1546. }
  1547. /**
  1548. * Creates some terms and a node, then tests the tokens generated from them.
  1549. */
  1550. function testTaxonomyTokenReplacement() {
  1551. global $language;
  1552. // Create two taxonomy terms.
  1553. $term1 = $this->createTerm($this->vocabulary);
  1554. $term2 = $this->createTerm($this->vocabulary);
  1555. // Edit $term2, setting $term1 as parent.
  1556. $edit = array();
  1557. $edit['name'] = '<blink>Blinking Text</blink>';
  1558. $edit['parent[]'] = array($term1->tid);
  1559. $this->drupalPost('taxonomy/term/' . $term2->tid . '/edit', $edit, t('Save'));
  1560. // Create node with term2.
  1561. $edit = array();
  1562. $node = $this->drupalCreateNode(array('type' => 'article'));
  1563. $edit[$this->instance['field_name'] . '[' . $this->langcode . '][]'] = $term2->tid;
  1564. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  1565. // Generate and test sanitized tokens for term1.
  1566. $tests = array();
  1567. $tests['[term:tid]'] = $term1->tid;
  1568. $tests['[term:name]'] = check_plain($term1->name);
  1569. $tests['[term:description]'] = check_markup($term1->description, $term1->format);
  1570. $tests['[term:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
  1571. $tests['[term:node-count]'] = 0;
  1572. $tests['[term:parent:name]'] = '[term:parent:name]';
  1573. $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
  1574. foreach ($tests as $input => $expected) {
  1575. $output = token_replace($input, array('term' => $term1), array('language' => $language));
  1576. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1577. }
  1578. // Generate and test sanitized tokens for term2.
  1579. $tests = array();
  1580. $tests['[term:tid]'] = $term2->tid;
  1581. $tests['[term:name]'] = check_plain($term2->name);
  1582. $tests['[term:description]'] = check_markup($term2->description, $term2->format);
  1583. $tests['[term:url]'] = url('taxonomy/term/' . $term2->tid, array('absolute' => TRUE));
  1584. $tests['[term:node-count]'] = 1;
  1585. $tests['[term:parent:name]'] = check_plain($term1->name);
  1586. $tests['[term:parent:url]'] = url('taxonomy/term/' . $term1->tid, array('absolute' => TRUE));
  1587. $tests['[term:parent:parent:name]'] = '[term:parent:parent:name]';
  1588. $tests['[term:vocabulary:name]'] = check_plain($this->vocabulary->name);
  1589. // Test to make sure that we generated something for each token.
  1590. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1591. foreach ($tests as $input => $expected) {
  1592. $output = token_replace($input, array('term' => $term2), array('language' => $language));
  1593. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1594. }
  1595. // Generate and test unsanitized tokens.
  1596. $tests['[term:name]'] = $term2->name;
  1597. $tests['[term:description]'] = $term2->description;
  1598. $tests['[term:parent:name]'] = $term1->name;
  1599. $tests['[term:vocabulary:name]'] = $this->vocabulary->name;
  1600. foreach ($tests as $input => $expected) {
  1601. $output = token_replace($input, array('term' => $term2), array('language' => $language, 'sanitize' => FALSE));
  1602. $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy term token %token replaced.', array('%token' => $input)));
  1603. }
  1604. // Generate and test sanitized tokens.
  1605. $tests = array();
  1606. $tests['[vocabulary:vid]'] = $this->vocabulary->vid;
  1607. $tests['[vocabulary:name]'] = check_plain($this->vocabulary->name);
  1608. $tests['[vocabulary:description]'] = filter_xss($this->vocabulary->description);
  1609. $tests['[vocabulary:node-count]'] = 1;
  1610. $tests['[vocabulary:term-count]'] = 2;
  1611. // Test to make sure that we generated something for each token.
  1612. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
  1613. foreach ($tests as $input => $expected) {
  1614. $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language));
  1615. $this->assertEqual($output, $expected, format_string('Sanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
  1616. }
  1617. // Generate and test unsanitized tokens.
  1618. $tests['[vocabulary:name]'] = $this->vocabulary->name;
  1619. $tests['[vocabulary:description]'] = $this->vocabulary->description;
  1620. foreach ($tests as $input => $expected) {
  1621. $output = token_replace($input, array('vocabulary' => $this->vocabulary), array('language' => $language, 'sanitize' => FALSE));
  1622. $this->assertEqual($output, $expected, format_string('Unsanitized taxonomy vocabulary token %token replaced.', array('%token' => $input)));
  1623. }
  1624. }
  1625. }
  1626. /**
  1627. * Tests for verifying that taxonomy pages use the correct theme.
  1628. */
  1629. class TaxonomyThemeTestCase extends TaxonomyWebTestCase {
  1630. public static function getInfo() {
  1631. return array(
  1632. 'name' => 'Taxonomy theme switching',
  1633. 'description' => 'Verifies that various taxonomy pages use the expected theme.',
  1634. 'group' => 'Taxonomy',
  1635. );
  1636. }
  1637. function setUp() {
  1638. parent::setUp();
  1639. // Make sure we are using distinct default and administrative themes for
  1640. // the duration of these tests.
  1641. variable_set('theme_default', 'bartik');
  1642. variable_set('admin_theme', 'seven');
  1643. // Create and log in as a user who has permission to add and edit taxonomy
  1644. // terms and view the administrative theme.
  1645. $admin_user = $this->drupalCreateUser(array('administer taxonomy', 'view the administration theme'));
  1646. $this->drupalLogin($admin_user);
  1647. }
  1648. /**
  1649. * Test the theme used when adding, viewing and editing taxonomy terms.
  1650. */
  1651. function testTaxonomyTermThemes() {
  1652. // Adding a term to a vocabulary is considered an administrative action and
  1653. // should use the administrative theme.
  1654. $vocabulary = $this->createVocabulary();
  1655. $this->drupalGet('admin/structure/taxonomy/' . $vocabulary->machine_name . '/add');
  1656. $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for adding a taxonomy term.");
  1657. // Viewing a taxonomy term should use the default theme.
  1658. $term = $this->createTerm($vocabulary);
  1659. $this->drupalGet('taxonomy/term/' . $term->tid);
  1660. $this->assertRaw('bartik/css/style.css', "The default theme's CSS appears on the page for viewing a taxonomy term.");
  1661. // Editing a taxonomy term should use the same theme as adding one.
  1662. $this->drupalGet('taxonomy/term/' . $term->tid . '/edit');
  1663. $this->assertRaw('seven/style.css', "The administrative theme's CSS appears on the page for editing a taxonomy term.");
  1664. }
  1665. }
  1666. /**
  1667. * Tests the functionality of EntityFieldQuery for taxonomy entities.
  1668. */
  1669. class TaxonomyEFQTestCase extends TaxonomyWebTestCase {
  1670. public static function getInfo() {
  1671. return array(
  1672. 'name' => 'Taxonomy EntityFieldQuery',
  1673. 'description' => 'Verifies operation of a taxonomy-based EntityFieldQuery.',
  1674. 'group' => 'Taxonomy',
  1675. );
  1676. }
  1677. function setUp() {
  1678. parent::setUp();
  1679. $this->admin_user = $this->drupalCreateUser(array('administer taxonomy'));
  1680. $this->drupalLogin($this->admin_user);
  1681. $this->vocabulary = $this->createVocabulary();
  1682. }
  1683. /**
  1684. * Tests that a basic taxonomy EntityFieldQuery works.
  1685. */
  1686. function testTaxonomyEFQ() {
  1687. $terms = array();
  1688. for ($i = 0; $i < 5; $i++) {
  1689. $term = $this->createTerm($this->vocabulary);
  1690. $terms[$term->tid] = $term;
  1691. }
  1692. $query = new EntityFieldQuery();
  1693. $query->entityCondition('entity_type', 'taxonomy_term');
  1694. $result = $query->execute();
  1695. $result = $result['taxonomy_term'];
  1696. asort($result);
  1697. $this->assertEqual(array_keys($terms), array_keys($result), 'Taxonomy terms were retrieved by EntityFieldQuery.');
  1698. // Create a second vocabulary and five more terms.
  1699. $vocabulary2 = $this->createVocabulary();
  1700. $terms2 = array();
  1701. for ($i = 0; $i < 5; $i++) {
  1702. $term = $this->createTerm($vocabulary2);
  1703. $terms2[$term->tid] = $term;
  1704. }
  1705. $query = new EntityFieldQuery();
  1706. $query->entityCondition('entity_type', 'taxonomy_term');
  1707. $query->entityCondition('bundle', $vocabulary2->machine_name);
  1708. $result = $query->execute();
  1709. $result = $result['taxonomy_term'];
  1710. asort($result);
  1711. $this->assertEqual(array_keys($terms2), array_keys($result), format_string('Taxonomy terms from the %name vocabulary were retrieved by EntityFieldQuery.', array('%name' => $vocabulary2->name)));
  1712. }
  1713. }