taxonomy.test 77 KB

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