entity.test 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123
  1. <?php
  2. /**
  3. * @file
  4. * Entity CRUD API tests.
  5. */
  6. /**
  7. * Common parent class containing common helpers.
  8. */
  9. abstract class EntityWebTestCase extends DrupalWebTestCase {
  10. /**
  11. * Creates a new vocabulary.
  12. */
  13. protected function createVocabulary() {
  14. $vocab = entity_create('taxonomy_vocabulary', array(
  15. 'name' => $this->randomName(),
  16. 'machine_name' => drupal_strtolower($this->randomName()),
  17. 'description' => $this->randomName(),
  18. ));
  19. entity_save('taxonomy_vocabulary', $vocab);
  20. return $vocab;
  21. }
  22. /**
  23. * Creates a random file of the given type.
  24. */
  25. protected function createFile($file_type = 'text') {
  26. // Create a managed file.
  27. $file = current($this->drupalGetTestFiles($file_type));
  28. // Set additional file properties and save it.
  29. $file->filemime = file_get_mimetype($file->filename);
  30. $file->uid = 1;
  31. $file->timestamp = REQUEST_TIME;
  32. $file->filesize = filesize($file->uri);
  33. $file->status = 0;
  34. file_save($file);
  35. return $file;
  36. }
  37. }
  38. /**
  39. * Test basic API.
  40. */
  41. class EntityAPITestCase extends EntityWebTestCase {
  42. public static function getInfo() {
  43. return array(
  44. 'name' => 'Entity CRUD',
  45. 'description' => 'Tests basic CRUD API functionality.',
  46. 'group' => 'Entity API',
  47. );
  48. }
  49. function setUp() {
  50. parent::setUp('entity', 'entity_test');
  51. }
  52. /**
  53. * Tests CRUD.
  54. */
  55. function testCRUD() {
  56. module_enable(array('entity_feature'));
  57. $user1 = $this->drupalCreateUser();
  58. // Create test entities for the user1 and unrelated to a user.
  59. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => $user1->uid));
  60. $entity->save();
  61. $entity = entity_create('entity_test', array('name' => 'test2', 'uid' => $user1->uid));
  62. $entity->save();
  63. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => NULL));
  64. $entity->save();
  65. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test')));
  66. $this->assertEqual($entities[0]->name, 'test', 'Created and loaded entity.');
  67. $this->assertEqual($entities[1]->name, 'test', 'Created and loaded entity.');
  68. $results = entity_test_load_multiple(array($entity->pid));
  69. $loaded = array_pop($results);
  70. $this->assertEqual($loaded->pid, $entity->pid, 'Loaded the entity unrelated to a user.');
  71. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test2')));
  72. $entities[0]->delete();
  73. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test2')));
  74. $this->assertEqual($entities, array(), 'Entity successfully deleted.');
  75. $entity->save();
  76. $this->assertEqual($entity->pid, $loaded->pid, 'Entity successfully updated.');
  77. // Try deleting multiple test entities by deleting all.
  78. $pids = array_keys(entity_test_load_multiple(FALSE));
  79. entity_test_delete_multiple($pids);
  80. }
  81. /**
  82. * Tests CRUD for entities supporting revisions.
  83. */
  84. function testCRUDRevisisions() {
  85. module_enable(array('entity_feature'));
  86. // Add text field to entity.
  87. $field_info = array(
  88. 'field_name' => 'field_text',
  89. 'type' => 'text',
  90. 'entity_types' => array('entity_test2'),
  91. );
  92. field_create_field($field_info);
  93. $instance = array(
  94. 'label' => 'Text Field',
  95. 'field_name' => 'field_text',
  96. 'entity_type' => 'entity_test2',
  97. 'bundle' => 'entity_test2',
  98. 'settings' => array(),
  99. 'required' => FALSE,
  100. );
  101. field_create_instance($instance);
  102. // Create a test entity.
  103. $entity_first_revision = entity_create('entity_test2', array('title' => 'first revision', 'name' => 'main', 'uid' => 1));
  104. $entity_first_revision->field_text[LANGUAGE_NONE][0]['value'] = 'first revision text';
  105. entity_save('entity_test2', $entity_first_revision);
  106. $entities = array_values(entity_load('entity_test2', FALSE));
  107. $this->assertEqual(count($entities), 1, 'Entity created.');
  108. $this->assertTrue($entities[0]->default_revision, 'Initial entity revision is marked as default revision.');
  109. // Saving the entity in revision mode should create a new revision.
  110. $entity_second_revision = clone $entity_first_revision;
  111. $entity_second_revision->title = 'second revision';
  112. $entity_second_revision->is_new_revision = TRUE;
  113. $entity_second_revision->default_revision = TRUE;
  114. $entity_second_revision->field_text[LANGUAGE_NONE][0]['value'] = 'second revision text';
  115. entity_save('entity_test2', $entity_second_revision);
  116. $this->assertNotEqual($entity_second_revision->revision_id, $entity_first_revision->revision_id, 'Saving an entity in new revision mode creates a revision.');
  117. $this->assertTrue($entity_second_revision->default_revision, 'New entity revision is marked as default revision.');
  118. // Check the saved entity.
  119. $entity = current(entity_load('entity_test2', array($entity_first_revision->pid), array(), TRUE));
  120. $this->assertNotEqual($entity->title, $entity_first_revision->title, 'Default revision was changed.');
  121. // Create third revision that is not default.
  122. $entity_third_revision = clone $entity_first_revision;
  123. $entity_third_revision->title = 'third revision';
  124. $entity_third_revision->is_new_revision = TRUE;
  125. $entity_third_revision->default_revision = FALSE;
  126. $entity_third_revision->field_text[LANGUAGE_NONE][0]['value'] = 'third revision text';
  127. entity_save('entity_test2', $entity_third_revision);
  128. $this->assertNotEqual($entity_second_revision->revision_id, $entity_third_revision->revision_id, 'Saving an entity in revision mode creates a revision.');
  129. $this->assertFalse($entity_third_revision->default_revision, 'Entity revision is not marked as default revision.');
  130. $entity = current(entity_load('entity_test2', array($entity_first_revision->pid), array(), TRUE));
  131. $this->assertEqual($entity->title, $entity_second_revision->title, 'Default revision was not changed.');
  132. $this->assertEqual($entity->field_text[LANGUAGE_NONE][0]['value'], $entity_second_revision->field_text[LANGUAGE_NONE][0]['value'], 'Default revision text field was not changed.');
  133. // Load not default revision.
  134. $revision = entity_revision_load('entity_test2', $entity_third_revision->revision_id);
  135. $this->assertEqual($revision->revision_id, $entity_third_revision->revision_id, 'Revision successfully loaded.');
  136. $this->assertFalse($revision->default_revision, 'Entity revision is not marked as default revision after loading.');
  137. // Save not default revision.
  138. $entity_third_revision->title = 'third revision updated';
  139. $entity_third_revision->field_text[LANGUAGE_NONE][0]['value'] = 'third revision text updated';
  140. entity_save('entity_test2', $entity_third_revision);
  141. // Ensure that not default revision has been changed.
  142. $entity = entity_revision_load('entity_test2', $entity_third_revision->revision_id);
  143. $this->assertEqual($entity->title, 'third revision updated', 'Not default revision was updated successfully.');
  144. $this->assertEqual($entity->field_text[LANGUAGE_NONE][0]['value'], 'third revision text updated', 'Not default revision field was updated successfully.');
  145. // Ensure that default revision has not been changed.
  146. $entity = current(entity_load('entity_test2', array($entity_first_revision->pid), array(), TRUE));
  147. $this->assertEqual($entity->title, $entity_second_revision->title, 'Default revision was not changed.');
  148. // Try to delete default revision.
  149. $result = entity_revision_delete('entity_test2', $entity_second_revision->revision_id);
  150. $this->assertFalse($result, 'Default revision cannot be deleted.');
  151. // Make sure default revision is still set after trying to delete it.
  152. $entity = current(entity_load('entity_test2', array($entity_first_revision->pid), array(), TRUE));
  153. $this->assertEqual($entity->revision_id, $entity_second_revision->revision_id, 'Second revision is still default.');
  154. // Delete first revision.
  155. $result = entity_revision_delete('entity_test2', $entity_first_revision->revision_id);
  156. $this->assertTrue($result, 'Not default revision deleted.');
  157. $entity = entity_revision_load('entity_test2', $entity_first_revision->revision_id);
  158. $this->assertFalse($entity, 'First revision deleted.');
  159. // Delete the entity and make sure third revision has been deleted as well.
  160. entity_delete('entity_test2', $entity_second_revision->pid);
  161. $entity_info = entity_get_info('entity_test2');
  162. $result = db_select($entity_info['revision table'])
  163. ->condition('revision_id', $entity_third_revision->revision_id)
  164. ->countQuery()
  165. ->execute()
  166. ->fetchField();
  167. $this->assertEqual($result, 0, 'Entity deleted with its all revisions.');
  168. }
  169. /**
  170. * Tests CRUD API functions: entity_(create|delete|save)
  171. */
  172. function testCRUDAPIfunctions() {
  173. module_enable(array('entity_feature'));
  174. $user1 = $this->drupalCreateUser();
  175. // Create test entities for the user1 and unrelated to a user.
  176. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => $user1->uid));
  177. entity_save('entity_test', $entity);
  178. $entity = entity_create('entity_test', array('name' => 'test2', 'uid' => $user1->uid));
  179. entity_save('entity_test', $entity);
  180. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => NULL));
  181. entity_save('entity_test', $entity);
  182. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test')));
  183. $this->assertEqual($entities[0]->name, 'test', 'Created and loaded entity.');
  184. $this->assertEqual($entities[1]->name, 'test', 'Created and loaded entity.');
  185. // Test getting the entity label, which is the used test-type's label.
  186. $label = entity_label('entity_test', $entities[0]);
  187. $this->assertEqual($label, 'label', 'Default label returned.');
  188. $results = entity_test_load_multiple(array($entity->pid));
  189. $loaded = array_pop($results);
  190. $this->assertEqual($loaded->pid, $entity->pid, 'Loaded the entity unrelated to a user.');
  191. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test2')));
  192. entity_delete('entity_test', $entities[0]->pid);
  193. $entities = array_values(entity_test_load_multiple(FALSE, array('name' => 'test2')));
  194. $this->assertEqual($entities, array(), 'Entity successfully deleted.');
  195. entity_save('entity_test', $entity);
  196. $this->assertEqual($entity->pid, $loaded->pid, 'Entity successfully updated.');
  197. // Try deleting multiple test entities by deleting all.
  198. $pids = array_keys(entity_test_load_multiple(FALSE));
  199. entity_delete_multiple('entity_test', $pids);
  200. }
  201. /**
  202. * Test loading entities defined in code.
  203. */
  204. function testExportables() {
  205. module_enable(array('entity_feature'));
  206. $types = entity_load_multiple_by_name('entity_test_type', array('test2', 'test'));
  207. $this->assertEqual(array_keys($types), array('test2', 'test'), 'Entities have been loaded in the order as specified.');
  208. $this->assertEqual($types['test']->label, 'label', 'Default type loaded.');
  209. $this->assertTrue($types['test']->status & ENTITY_IN_CODE && !($types['test']->status & ENTITY_CUSTOM), 'Default type status is correct.');
  210. // Test using a condition, which has to be applied on the defaults.
  211. $types = entity_load_multiple_by_name('entity_test_type', FALSE, array('label' => 'label'));
  212. $this->assertEqual($types['test']->label, 'label', 'Condition to default type applied.');
  213. $types['test']->label = 'modified';
  214. $types['test']->save();
  215. // Ensure loading the changed entity works.
  216. $types = entity_load_multiple_by_name('entity_test_type', FALSE, array('label' => 'modified'));
  217. $this->assertEqual($types['test']->label, 'modified', 'Modified type loaded.');
  218. // Clear the cache to simulate a new page load.
  219. entity_get_controller('entity_test_type')->resetCache();
  220. // Test loading using a condition again, now they default may not appear any
  221. // more as it's overridden by an entity with another label.
  222. $types = entity_load_multiple_by_name('entity_test_type', FALSE, array('label' => 'label'));
  223. $this->assertTrue(empty($types), 'Conditions are applied to the overridden entity only.');
  224. // But the overridden entity has to appear with another condition.
  225. $types = entity_load_multiple_by_name('entity_test_type', FALSE, array('label' => 'modified'));
  226. $this->assertEqual($types['test']->label, 'modified', 'Modified default type loaded by condition.');
  227. $types = entity_load_multiple_by_name('entity_test_type', array('test', 'test2'));
  228. $this->assertEqual($types['test']->label, 'modified', 'Modified default type loaded by id.');
  229. $this->assertTrue(entity_has_status('entity_test_type', $types['test'], ENTITY_OVERRIDDEN), 'Status of overridden type is correct.');
  230. // Test rebuilding the defaults and make sure overridden entities stay.
  231. entity_defaults_rebuild();
  232. $types = entity_load_multiple_by_name('entity_test_type', array('test', 'test2'));
  233. $this->assertEqual($types['test']->label, 'modified', 'Overridden entity is still overridden.');
  234. $this->assertTrue(entity_has_status('entity_test_type', $types['test'], ENTITY_OVERRIDDEN), 'Status of overridden type is correct.');
  235. // Test reverting.
  236. $types['test']->delete();
  237. $types = entity_load_multiple_by_name('entity_test_type', array('test', 'test2'));
  238. $this->assertEqual($types['test']->label, 'label', 'Entity has been reverted.');
  239. // Test loading an exportable by its numeric id.
  240. $result = entity_load_multiple_by_name('entity_test_type', array($types['test']->id));
  241. $this->assertTrue(isset($result['test']), 'Exportable entity loaded by the numeric id.');
  242. // Test exporting an entity to JSON.
  243. $serialized_string = $types['test']->export();
  244. $data = drupal_json_decode($serialized_string);
  245. $this->assertNotNull($data, 'Exported entity is valid JSON.');
  246. $import = entity_import('entity_test_type', $serialized_string);
  247. $this->assertTrue(get_class($import) == get_class($types['test']) && $types['test']->label == $import->label, 'Successfully exported entity to code.');
  248. $this->assertTrue(!isset($import->status), 'Exportable status has not been exported to code.');
  249. // Test disabling the module providing the defaults in code.
  250. $types = entity_load_multiple_by_name('entity_test_type', array('test', 'test2'));
  251. $types['test']->label = 'modified';
  252. $types['test']->save();
  253. module_disable(array('entity_feature'));
  254. // Make sure the overridden entity stays and the other one is deleted.
  255. entity_get_controller('entity_test_type')->resetCache();
  256. $test = entity_load_single('entity_test_type', 'test');
  257. $this->assertTrue(!empty($test) && $test->label == 'modified', 'Overidden entity is still available.');
  258. $this->assertTrue(!empty($test) && !entity_has_status('entity_test_type', $test, ENTITY_IN_CODE) && entity_has_status('entity_test_type', $test, ENTITY_CUSTOM), 'Overidden entity is now marked as custom.');
  259. $test2 = entity_load_single('entity_test_type', 'test2');
  260. $this->assertFalse($test2, 'Default entity has disappeared.');
  261. }
  262. /**
  263. * Make sure insert() and update() hooks for exportables are invoked.
  264. */
  265. function testExportableHooks() {
  266. $_SESSION['entity_hook_test'] = array();
  267. // Enabling the module should invoke the enabled hook for the other
  268. // entities provided in code.
  269. module_enable(array('entity_feature'));
  270. $insert = array('main', 'test', 'test2');
  271. $this->assertTrue($_SESSION['entity_hook_test']['entity_insert'] == $insert, 'Hook entity_insert has been invoked.');
  272. $this->assertTrue($_SESSION['entity_hook_test']['entity_test_type_insert'] == $insert, 'Hook entity_test_type_insert has been invoked.');
  273. // Load a default entity and make sure the rebuilt logic only ran once.
  274. entity_load_single('entity_test_type', 'test');
  275. $this->assertTrue(!isset($_SESSION['entity_hook_test']['entity_test_type_update']), '"Entity-test-type" defaults have been rebuilt only once.');
  276. // Add a new test entity in DB and make sure the hook is invoked too.
  277. $test3 = entity_create('entity_test_type', array(
  278. 'name' => 'test3',
  279. 'label' => 'label',
  280. 'weight' => 0,
  281. ));
  282. $test3->save();
  283. $insert[] = 'test3';
  284. $this->assertTrue($_SESSION['entity_hook_test']['entity_insert'] == $insert, 'Hook entity_insert has been invoked.');
  285. $this->assertTrue($_SESSION['entity_hook_test']['entity_test_type_insert'] == $insert, 'Hook entity_test_type_insert has been invoked.');
  286. // Now override the 'test' entity and make sure it invokes the update hook.
  287. $result = entity_load_multiple_by_name('entity_test_type', array('test'));
  288. $result['test']->label = 'modified';
  289. $result['test']->save();
  290. $this->assertTrue($_SESSION['entity_hook_test']['entity_update'] == array('test'), 'Hook entity_update has been invoked.');
  291. $this->assertTrue($_SESSION['entity_hook_test']['entity_test_type_update'] == array('test'), 'Hook entity_test_type_update has been invoked.');
  292. // 'test' has to remain enabled, as it has been overridden.
  293. $delete = array('main', 'test2');
  294. module_disable(array('entity_feature'));
  295. $this->assertTrue($_SESSION['entity_hook_test']['entity_delete'] == $delete, 'Hook entity_deleted has been invoked.');
  296. $this->assertTrue($_SESSION['entity_hook_test']['entity_test_type_delete'] == $delete, 'Hook entity_test_type_deleted has been invoked.');
  297. // Now make sure 'test' is not overridden any more, but custom.
  298. $result = entity_load_multiple_by_name('entity_test_type', array('test'));
  299. $this->assertTrue(!$result['test']->hasStatus(ENTITY_OVERRIDDEN), 'Entity is not marked as overridden any more.');
  300. $this->assertTrue(entity_has_status('entity_test_type', $result['test'], ENTITY_CUSTOM), 'Entity is marked as custom.');
  301. // Test deleting the remaining entities from DB.
  302. entity_delete_multiple('entity_test_type', array('test', 'test3'));
  303. $delete[] = 'test';
  304. $delete[] = 'test3';
  305. $this->assertTrue($_SESSION['entity_hook_test']['entity_delete'] == $delete, 'Hook entity_deleted has been invoked.');
  306. $this->assertTrue($_SESSION['entity_hook_test']['entity_test_type_delete'] == $delete, 'Hook entity_test_type_deleted has been invoked.');
  307. }
  308. /**
  309. * Tests determining changes.
  310. */
  311. function testChanges() {
  312. module_enable(array('entity_feature'));
  313. $types = entity_load_multiple_by_name('entity_test_type');
  314. // Override the default entity, such it gets saved in the DB.
  315. $types['test']->label ='test_changes';
  316. $types['test']->save();
  317. // Now test an update without applying any changes.
  318. $types['test']->save();
  319. $this->assertEqual($types['test']->label, 'test_changes', 'No changes have been determined.');
  320. // Apply changes.
  321. $types['test']->label = 'updated';
  322. $types['test']->save();
  323. // The hook implementations entity_test_entity_test_type_presave() and
  324. // entity_test_entity_test_type_update() determine changes and change the
  325. // label.
  326. $this->assertEqual($types['test']->label, 'updated_presave_update', 'Changes have been determined.');
  327. // Test the static load cache to be cleared.
  328. $types = entity_load_multiple_by_name('entity_test_type');
  329. $this->assertEqual($types['test']->label, 'updated_presave', 'Static cache has been cleared.');
  330. }
  331. /**
  332. * Tests viewing entites.
  333. */
  334. function testRendering() {
  335. module_enable(array('entity_feature'));
  336. $user1 = $this->drupalCreateUser();
  337. // Create test entities for the user1 and unrelated to a user.
  338. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => $user1->uid));
  339. $render = $entity->view();
  340. $output = drupal_render($render);
  341. // The entity class adds the user name to the output. Verify it is there.
  342. $this->assertTrue(strpos($output, format_username($user1)) !== FALSE, 'Entity has been rendered');
  343. }
  344. /**
  345. * Test uninstall of the entity_test module.
  346. */
  347. function testUninstall() {
  348. // Add a test type and add a field instance, uninstall, then re-install and
  349. // make sure the field instance can be re-created.
  350. $test_type = entity_create('entity_test_type', array(
  351. 'name' => 'test',
  352. 'label' => 'label',
  353. 'weight' => 0,
  354. ));
  355. $test_type->save();
  356. $field = array(
  357. 'field_name' => 'field_test_fullname',
  358. 'type' => 'text',
  359. 'cardinality' => 1,
  360. 'translatable' => FALSE,
  361. );
  362. field_create_field($field);
  363. $instance = array(
  364. 'entity_type' => 'entity_test',
  365. 'field_name' => 'field_test_fullname',
  366. 'bundle' => 'test',
  367. 'label' => 'Full name',
  368. 'description' => 'Specify your first and last name.',
  369. 'widget' => array(
  370. 'type' => 'text_textfield',
  371. 'weight' => 0,
  372. ),
  373. );
  374. field_create_instance($instance);
  375. // Uninstallation has to remove all bundles, thus also field instances.
  376. module_disable(array('entity_test'));
  377. require_once DRUPAL_ROOT . '/includes/install.inc';
  378. drupal_uninstall_modules(array('entity_test'));
  379. // Make sure the instance has been deleted.
  380. $instance_read = field_read_instance('entity_test', 'field_test_fullname', 'test', array('include_inactive' => 1));
  381. $this->assertFalse((bool) $instance_read, 'Field instance has been deleted.');
  382. // Ensure re-creating the same instance now works.
  383. module_enable(array('entity_test'));
  384. $test_type = entity_create('entity_test_type', array(
  385. 'name' => 'test',
  386. 'label' => 'label',
  387. 'weight' => 0,
  388. ));
  389. $test_type->save();
  390. field_create_field($field);
  391. field_create_instance($instance);
  392. $instance_read = field_info_instance('entity_test', 'field_test_fullname', 'test');
  393. $this->assertTrue((bool) $instance_read, 'Field instance has been re-created.');
  394. }
  395. }
  396. /**
  397. * Test the generated Rules integration.
  398. */
  399. class EntityAPIRulesIntegrationTestCase extends EntityWebTestCase {
  400. public static function getInfo() {
  401. return array(
  402. 'name' => 'Entity CRUD Rules integration',
  403. 'description' => 'Tests the Rules integration provided by the Entity CRUD API.',
  404. 'group' => 'Entity API',
  405. 'dependencies' => array('rules'),
  406. );
  407. }
  408. function setUp() {
  409. parent::setUp('entity', 'entity_test', 'rules');
  410. // Make sure the logger is enabled so the debug log is saved.
  411. variable_set('rules_debug_log', 1);
  412. }
  413. /**
  414. * Test the events.
  415. */
  416. function testEvents() {
  417. $rule = rules_reaction_rule();
  418. $rule->event('entity_test_presave');
  419. $rule->event('entity_test_insert');
  420. $rule->event('entity_test_update');
  421. $rule->event('entity_test_delete');
  422. $rule->action('drupal_message', array('message' => 'hello!'));
  423. $rule->save();
  424. rules_clear_cache(TRUE);
  425. // Let the events occur.
  426. $user1 = $this->drupalCreateUser();
  427. RulesLog::logger()->clear();
  428. $entity = entity_create('entity_test', array('name' => 'test', 'uid' => $user1->uid));
  429. $entity->save();
  430. $entity->name = 'update';
  431. $entity->save();
  432. $entity->delete();
  433. // Now there should have been 5 events, 2 times presave and once insert,
  434. // update and delete.
  435. $count = substr_count(RulesLog::logger()->render(), '0 ms Reacting on event');
  436. $this->assertTrue($count == 5, 'Events have been properly invoked.');
  437. RulesLog::logger()->checkLog();
  438. }
  439. }
  440. /**
  441. * Tests comments with node access.
  442. */
  443. class EntityAPICommentNodeAccessTestCase extends CommentHelperCase {
  444. public static function getInfo() {
  445. return array(
  446. 'name' => 'Entity API comment node access',
  447. 'description' => 'Test viewing comments on nodes with node access.',
  448. 'group' => 'Entity API',
  449. );
  450. }
  451. function setUp() {
  452. DrupalWebTestCase::setUp('comment', 'entity', 'node_access_test');
  453. node_access_rebuild();
  454. // Create test node and user with simple node access permission. The
  455. // 'node test view' permission is implemented and granted by the
  456. // node_access_test module.
  457. $this->accessUser = $this->drupalCreateUser(array('access comments', 'post comments', 'edit own comments', 'node test view'));
  458. $this->noAccessUser = $this->drupalCreateUser(array('administer comments'));
  459. $this->node = $this->drupalCreateNode(array('type' => 'article', 'uid' => $this->accessUser->uid));
  460. }
  461. /**
  462. * Tests comment access when node access is enabled.
  463. */
  464. function testCommentNodeAccess() {
  465. // Post comment.
  466. $this->drupalLogin($this->accessUser);
  467. $comment_text = $this->randomName();
  468. $comment = $this->postComment($this->node, $comment_text);
  469. $comment_loaded = comment_load($comment->id);
  470. $this->assertTrue($this->commentExists($comment), 'Comment found.');
  471. $this->drupalLogout();
  472. // Check access to node and associated comment for access user.
  473. $this->assertTrue(entity_access('view', 'node', $this->node, $this->accessUser), 'Access to view node was granted for access user');
  474. $this->assertTrue(entity_access('view', 'comment', $comment_loaded, $this->accessUser), 'Access to view comment was granted for access user');
  475. $this->assertTrue(entity_access('update', 'comment', $comment_loaded, $this->accessUser), 'Access to update comment was granted for access user');
  476. $this->assertFalse(entity_access('delete', 'comment', $comment_loaded, $this->accessUser), 'Access to delete comment was denied for access user');
  477. // Check access to node and associated comment for no access user.
  478. $this->assertFalse(entity_access('view', 'node', $this->node, $this->noAccessUser), 'Access to view node was denied for no access user');
  479. $this->assertFalse(entity_access('view', 'comment', $comment_loaded, $this->noAccessUser), 'Access to view comment was denied for no access user');
  480. $this->assertFalse(entity_access('update', 'comment', $comment_loaded, $this->noAccessUser), 'Access to update comment was denied for no access user');
  481. $this->assertFalse(entity_access('delete', 'comment', $comment_loaded, $this->noAccessUser), 'Access to delete comment was denied for no access user');
  482. }
  483. }
  484. /**
  485. * Test the i18n integration.
  486. */
  487. class EntityAPIi18nItegrationTestCase extends EntityWebTestCase {
  488. public static function getInfo() {
  489. return array(
  490. 'name' => 'Entity CRUD i18n integration',
  491. 'description' => 'Tests the i18n integration provided by the Entity CRUD API.',
  492. 'group' => 'Entity API',
  493. 'dependencies' => array('i18n_string'),
  494. );
  495. }
  496. function setUp() {
  497. parent::setUp('entity_test_i18n');
  498. $this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes', 'administer languages', 'administer content types', 'administer blocks', 'access administration pages'));
  499. $this->drupalLogin($this->admin_user);
  500. $this->addLanguage('de');
  501. }
  502. /**
  503. * Copied from i18n module (class Drupali18nTestCase).
  504. *
  505. * We cannot extend from Drupali18nTestCase as else the test-bot would die.
  506. */
  507. public function addLanguage($language_code) {
  508. // Check to make sure that language has not already been installed.
  509. $this->drupalGet('admin/config/regional/language');
  510. if (strpos($this->drupalGetContent(), 'enabled[' . $language_code . ']') === FALSE) {
  511. // Doesn't have language installed so add it.
  512. $edit = array();
  513. $edit['langcode'] = $language_code;
  514. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  515. // Make sure we are not using a stale list.
  516. drupal_static_reset('language_list');
  517. $languages = language_list('language');
  518. $this->assertTrue(array_key_exists($language_code, $languages), t('Language was installed successfully.'));
  519. if (array_key_exists($language_code, $languages)) {
  520. $this->assertRaw(t('The language %language has been created and can now be used. More information is available on the <a href="@locale-help">help screen</a>.', array('%language' => $languages[$language_code]->name, '@locale-help' => url('admin/help/locale'))), t('Language has been created.'));
  521. }
  522. }
  523. elseif ($this->xpath('//input[@type="checkbox" and @name=:name and @checked="checked"]', array(':name' => 'enabled[' . $language_code . ']'))) {
  524. // It's installed and enabled. No need to do anything.
  525. $this->assertTrue(true, 'Language [' . $language_code . '] already installed and enabled.');
  526. }
  527. else {
  528. // It's installed but not enabled. Enable it.
  529. $this->assertTrue(true, 'Language [' . $language_code . '] already installed.');
  530. $this->drupalPost(NULL, array('enabled[' . $language_code . ']' => TRUE), t('Save configuration'));
  531. $this->assertRaw(t('Configuration saved.'), t('Language successfully enabled.'));
  532. }
  533. }
  534. /**
  535. * Tests the provided default controller.
  536. */
  537. function testDefaultController() {
  538. // Create test entities for the user1 and unrelated to a user.
  539. $entity = entity_create('entity_test_type', array(
  540. 'name' => 'test',
  541. 'uid' => $GLOBALS['user']->uid,
  542. 'label' => 'label-en',
  543. ));
  544. $entity->save();
  545. // Add a translation.
  546. i18n_string_textgroup('entity_test')->update_translation("entity_test_type:{$entity->name}:label", 'de', 'label-de');
  547. $default = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en');
  548. $translation = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en', 'de');
  549. $this->assertEqual($translation, 'label-de', 'Label has been translated.');
  550. $this->assertEqual($default, 'label-en', 'Default label retrieved.');
  551. // Test the helper method.
  552. $translation = $entity->getTranslation('label', 'de');
  553. $default = $entity->getTranslation('label');
  554. $this->assertEqual($translation, 'label-de', 'Label has been translated via the helper method.');
  555. $this->assertEqual($default, 'label-en', 'Default label retrieved via the helper method.');
  556. // Test updating and make sure the translation stays.
  557. $entity->name = 'test2';
  558. $entity->save();
  559. $translation = $entity->getTranslation('label', 'de');
  560. $this->assertEqual($translation, 'label-de', 'Translation survives a name change.');
  561. // Test using the wrapper to retrieve a translation.
  562. $wrapper = entity_metadata_wrapper('entity_test_type', $entity);
  563. $translation = $wrapper->language('de')->label->value();
  564. $this->assertEqual($translation, 'label-de', 'Translation retrieved via the wrapper.');
  565. // Test deleting.
  566. $entity->delete();
  567. $translation = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en', 'de');
  568. $this->assertEqual($translation, 'label-en', 'Translation has been deleted.');
  569. }
  570. }
  571. /**
  572. * Tests metadata wrappers.
  573. */
  574. class EntityMetadataTestCase extends EntityWebTestCase {
  575. public static function getInfo() {
  576. return array(
  577. 'name' => 'Metadata Wrapper',
  578. 'description' => 'Makes sure metadata wrapper are working right.',
  579. 'group' => 'Entity API',
  580. );
  581. }
  582. function setUp() {
  583. parent::setUp('entity', 'entity_test', 'locale');
  584. // Create a field having 4 values for testing multiple value support.
  585. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  586. $this->field = array('field_name' => $this->field_name, 'type' => 'text', 'cardinality' => 4);
  587. $this->field = field_create_field($this->field);
  588. $this->field_id = $this->field['id'];
  589. $this->instance = array(
  590. 'field_name' => $this->field_name,
  591. 'entity_type' => 'node',
  592. 'bundle' => 'page',
  593. 'label' => $this->randomName() . '_label',
  594. 'description' => $this->randomName() . '_description',
  595. 'weight' => mt_rand(0, 127),
  596. 'settings' => array(
  597. 'text_processing' => FALSE,
  598. ),
  599. 'widget' => array(
  600. 'type' => 'text_textfield',
  601. 'label' => 'Test Field',
  602. 'settings' => array(
  603. 'size' => 64,
  604. )
  605. )
  606. );
  607. field_create_instance($this->instance);
  608. // Make the body field and the node type 'page' translatable.
  609. $field = field_info_field('body');
  610. $field['translatable'] = TRUE;
  611. field_update_field($field);
  612. variable_set('language_content_type_page', 1);
  613. }
  614. /**
  615. * Creates a user and a node, then tests getting the properties.
  616. */
  617. function testEntityMetadataWrapper() {
  618. $account = $this->drupalCreateUser();
  619. // For testing sanitizing give the user a malicious user name
  620. $account = user_save($account, array('name' => '<b>BadName</b>'));
  621. $title = '<b>Is it bold?<b>';
  622. $body[LANGUAGE_NONE][0] = array('value' => '<b>The body & nothing.</b>', 'summary' => '<b>The body.</b>');
  623. $node = $this->drupalCreateNode(array('uid' => $account->uid, 'name' => $account->name, 'body' => $body, 'title' => $title, 'summary' => '', 'type' => 'page'));
  624. // First test without sanitizing.
  625. $wrapper = entity_metadata_wrapper('node', $node);
  626. $this->assertEqual('<b>Is it bold?<b>', $wrapper->title->value(), 'Getting a field value.');
  627. $this->assertEqual($node->title, $wrapper->title->raw(), 'Getting a raw property value.');
  628. // Test chaining.
  629. $this->assertEqual($account->mail, $wrapper->author->mail->value(), 'Testing chained usage.');
  630. $this->assertEqual($account->name, $wrapper->author->name->value(), 'Testing chained usage with callback and sanitizing.');
  631. // Test sanitized output.
  632. $options = array('sanitize' => TRUE);
  633. $this->assertEqual(check_plain('<b>Is it bold?<b>'), $wrapper->title->value($options), 'Getting sanitized field.');
  634. $this->assertEqual(filter_xss($node->name), $wrapper->author->name->value($options), 'Getting sanitized property with getter callback.');
  635. // Test getting an not existing property.
  636. try {
  637. echo $wrapper->dummy;
  638. $this->fail('Getting an not existing property.');
  639. }
  640. catch (EntityMetadataWrapperException $e) {
  641. $this->pass('Getting an not existing property.');
  642. }
  643. // Test setting.
  644. $wrapper->author = 0;
  645. $this->assertEqual(0, $wrapper->author->uid->value(), 'Setting a property.');
  646. try {
  647. $wrapper->url = 'dummy';
  648. $this->fail('Setting an unsupported property.');
  649. }
  650. catch (EntityMetadataWrapperException $e) {
  651. $this->pass('Setting an unsupported property.');
  652. }
  653. // Test value validation.
  654. $this->assertFalse($wrapper->author->name->validate(array(3)), 'Validation correctly checks for valid data types.');
  655. try {
  656. $wrapper->author->mail = 'foo';
  657. $this->fail('An invalid mail address has been set.');
  658. }
  659. catch (EntityMetadataWrapperException $e) {
  660. $this->pass('Setting an invalid mail address throws exception.');
  661. }
  662. // Test unsetting a required property.
  663. try {
  664. $wrapper->author = NULL;
  665. $this->fail('The required node author has been unset.');
  666. }
  667. catch (EntityMetadataWrapperException $e) {
  668. $this->pass('Unsetting the required node author throws an exception.');
  669. }
  670. // Test setting a referenced entity by id.
  671. $wrapper->author->set($GLOBALS['user']->uid);
  672. $this->assertEqual($wrapper->author->getIdentifier(), $GLOBALS['user']->uid, 'Get the identifier of a referenced entity.');
  673. $this->assertEqual($wrapper->author->uid->value(), $GLOBALS['user']->uid, 'Successfully set referenced entity using the identifier.');
  674. // Set by object.
  675. $wrapper->author->set($GLOBALS['user']);
  676. $this->assertEqual($wrapper->author->uid->value(), $GLOBALS['user']->uid, 'Successfully set referenced entity using the entity.');
  677. // Test getting by the field API processed values like the node body.
  678. $body_value = $wrapper->body->value;
  679. $this->assertEqual("<p>The body &amp; nothing.</p>\n", $body_value->value(), "Getting processed value.");
  680. $this->assertEqual("The body & nothing.\n", $body_value->value(array('decode' => TRUE)), "Decoded value.");
  681. $this->assertEqual("<b>The body & nothing.</b>", $body_value->raw(), "Raw body returned.");
  682. // Test getting the summary.
  683. $this->assertEqual("<p>The body.</p>\n", $wrapper->body->summary->value(), "Getting body summary.");
  684. $wrapper->body->set(array('value' => "<b>The second body.</b>"));
  685. $this->assertEqual("<p>The second body.</p>\n", $wrapper->body->value->value(), "Setting a processed field value and reading it again.");
  686. $this->assertEqual($node->body[LANGUAGE_NONE][0]['value'], "<b>The second body.</b>", 'Update appears in the wrapped entity.');
  687. $this->assert(isset($node->body[LANGUAGE_NONE][0]['safe_value']), 'Formatted text has been processed.');
  688. // Test translating the body on an English node.
  689. locale_add_language('de');
  690. $body['en'][0] = array('value' => '<b>English body.</b>', 'summary' => '<b>The body.</b>');
  691. $node = $this->drupalCreateNode(array('body' => $body, 'language' => 'en', 'type' => 'page'));
  692. $wrapper = entity_metadata_wrapper('node', $node);
  693. $wrapper->language('de');
  694. $languages = language_list();
  695. $this->assertEqual($wrapper->getPropertyLanguage(), $languages['de'], 'Wrapper language has been set to German');
  696. $this->assertEqual($wrapper->body->value->value(), "<p>English body.</p>\n", 'Language fallback on default language.');
  697. // Set a German text using the wrapper.
  698. $wrapper->body->set(array('value' => "<b>Der zweite Text.</b>"));
  699. $this->assertEqual($wrapper->body->value->value(), "<p>Der zweite Text.</p>\n", 'German body set and retrieved.');
  700. $wrapper->language(LANGUAGE_NONE);
  701. $this->assertEqual($wrapper->body->value->value(), "<p>English body.</p>\n", 'Default language text is still there.');
  702. // Test iterator.
  703. $type_info = entity_get_property_info('node');
  704. $this->assertFalse(array_diff_key($type_info['properties'], iterator_to_array($wrapper->getIterator())), 'Iterator is working.');
  705. foreach ($wrapper as $property) {
  706. $this->assertTrue($property instanceof EntityMetadataWrapper, 'Iterate over wrapper properties.');
  707. }
  708. // Test setting a new node.
  709. $node->title = 'foo';
  710. $wrapper->set($node);
  711. $this->assertEqual($wrapper->title->value(), 'foo', 'Changed the wrapped node.');
  712. // Test getting options lists.
  713. $this->assertEqual($wrapper->type->optionsList(), node_type_get_names(), 'Options list returned.');
  714. // Test making use of a generic 'entity' reference property the
  715. // 'entity_test' module provides. The property defaults to the node author.
  716. $this->assertEqual($wrapper->reference->uid->value(), $wrapper->author->getIdentifier(), 'Used generic entity reference property.');
  717. // Test updating a property of the generic entity reference.
  718. $wrapper->reference->name->set('foo');
  719. $this->assertEqual($wrapper->reference->name->value(), 'foo', 'Updated property of generic entity reference');
  720. // For testing, just point the reference to the node itself now.
  721. $wrapper->reference->set($wrapper);
  722. $this->assertEqual($wrapper->reference->nid->value(), $wrapper->getIdentifier(), 'Correctly updated the generic entity referenced property.');
  723. // Test saving and deleting.
  724. $wrapper->save();
  725. $wrapper->delete();
  726. $return = node_load($wrapper->getIdentifier());
  727. $this->assertFalse($return, "Node has been successfully deleted.");
  728. // Ensure changing the bundle changes available wrapper properties.
  729. $wrapper->type->set('article');
  730. $this->assertTrue(isset($wrapper->field_tags), 'Changing bundle changes available wrapper properties.');
  731. // Test labels.
  732. $user = $this->drupalCreateUser();
  733. user_save($user, array('roles' => array()));
  734. $wrapper->author = $user->uid;
  735. $this->assertEqual($wrapper->label(), $node->title, 'Entity label returned.');
  736. $this->assertEqual($wrapper->author->roles[0]->label(), t('authenticated user'), 'Label from options list returned');
  737. $this->assertEqual($wrapper->author->roles->label(), t('authenticated user'), 'Label for a list from options list returned');
  738. }
  739. /**
  740. * Test supporting multi-valued fields.
  741. */
  742. function testListMetadataWrappers() {
  743. $property = $this->field_name;
  744. $values = array();
  745. $values[LANGUAGE_NONE][0] = array('value' => '<b>2009-09-05</b>');
  746. $values[LANGUAGE_NONE][1] = array('value' => '2009-09-05');
  747. $values[LANGUAGE_NONE][2] = array('value' => '2009-08-05');
  748. $node = $this->drupalCreateNode(array('type' => 'page', $property => $values));
  749. $wrapper = entity_metadata_wrapper('node', $node);
  750. $this->assertEqual('<b>2009-09-05</b>', $wrapper->{$property}[0]->value(), 'Getting array entry.');
  751. $this->assertEqual('2009-09-05', $wrapper->{$property}->get(1)->value(), 'Getting array entry.');
  752. $this->assertEqual(3, count($wrapper->{$property}->value()), 'Getting the whole array.');
  753. // Test sanitizing
  754. $this->assertEqual(check_plain('<b>2009-09-05</b>'), $wrapper->{$property}[0]->value(array('sanitize' => TRUE)), 'Getting array entry.');
  755. // Test iterator
  756. $this->assertEqual(array_keys(iterator_to_array($wrapper->$property->getIterator())), array_keys($wrapper->$property->value()), 'Iterator is working.');
  757. foreach ($wrapper->$property as $p) {
  758. $this->assertTrue($p instanceof EntityMetadataWrapper, 'Iterate over list wrapper properties.');
  759. }
  760. // Make sure changing the array changes the actual entity property.
  761. $wrapper->{$property}[0] = '2009-10-05';
  762. unset($wrapper->{$property}[1], $wrapper->{$property}[2]);
  763. $this->assertEqual($wrapper->{$property}->value(), array('2009-10-05'), 'Setting multiple property values.');
  764. // Test setting an arbitrary list item.
  765. $list = array(0 => REQUEST_TIME);
  766. $wrapper = entity_metadata_wrapper('list<date>', $list);
  767. $wrapper[1] = strtotime('2009-09-05');
  768. $this->assertEqual($wrapper->value(), array(REQUEST_TIME, strtotime('2009-09-05')), 'Setting a list item.');
  769. $this->assertEqual($wrapper->count(), 2, 'List count is correct.');
  770. // Test using a list wrapper without data.
  771. $wrapper = entity_metadata_wrapper('list<date>');
  772. $info = array();
  773. foreach ($wrapper as $item) {
  774. $info[] = $item->info();
  775. }
  776. $this->assertTrue($info[0]['type'] == 'date', 'Iterated over empty list wrapper.');
  777. // Test using a list of entities with a list of term objects.
  778. $list = array();
  779. $list[] = entity_property_values_create_entity('taxonomy_term', array(
  780. 'name' => 'term 1',
  781. 'vocabulary' => 1,
  782. ))->save()->value();
  783. $list[] = entity_property_values_create_entity('taxonomy_term', array(
  784. 'name' => 'term 2',
  785. 'vocabulary' => 1,
  786. ))->save()->value();
  787. $wrapper = entity_metadata_wrapper('list<taxonomy_term>', $list);
  788. $this->assertTrue($wrapper[0]->name->value() == 'term 1', 'Used a list of entities.');
  789. // Test getting a list of identifiers.
  790. $ids = $wrapper->value(array('identifier' => TRUE));
  791. $this->assertTrue(!is_object($ids[0]), 'Get a list of entity ids.');
  792. $wrapper = entity_metadata_wrapper('list<taxonomy_term>', $ids);
  793. $this->assertTrue($wrapper[0]->name->value() == 'term 1', 'Created a list of entities with ids.');
  794. // Test with a list of generic entities. The list is expected to be a list
  795. // of entity wrappers, otherwise the entity type is unknown.
  796. $node = $this->drupalCreateNode(array('title' => 'node 1'));
  797. $list = array();
  798. $list[] = entity_metadata_wrapper('node', $node);
  799. $wrapper = entity_metadata_wrapper('list<entity>', $list);
  800. $this->assertEqual($wrapper[0]->title->value(), 'node 1', 'Wrapped node was found in generic list of entities.');
  801. }
  802. /**
  803. * Tests using the wrapper without any data.
  804. */
  805. function testWithoutData() {
  806. $wrapper = entity_metadata_wrapper('node', NULL, array('bundle' => 'page'));
  807. $this->assertTrue(isset($wrapper->title), 'Bundle properties have been added.');
  808. $info = $wrapper->author->mail->info();
  809. $this->assertTrue(!empty($info) && is_array($info) && isset($info['label']), 'Property info returned.');
  810. }
  811. /**
  812. * Test using access() method.
  813. */
  814. function testAccess() {
  815. // Test without data.
  816. $account = $this->drupalCreateUser(array('bypass node access'));
  817. $this->assertTrue(entity_access('view', 'node', NULL, $account), 'Access without data checked.');
  818. // Test with actual data.
  819. $values[LANGUAGE_NONE][0] = array('value' => '<b>2009-09-05</b>');
  820. $values[LANGUAGE_NONE][1] = array('value' => '2009-09-05');
  821. $node = $this->drupalCreateNode(array('type' => 'page', $this->field_name => $values));
  822. $this->assertTrue(entity_access('delete', 'node', $node, $account), 'Access with data checked.');
  823. // Test per property access without data.
  824. $account2 = $this->drupalCreateUser(array('bypass node access', 'administer nodes'));
  825. $wrapper = entity_metadata_wrapper('node', NULL, array('bundle' => 'page'));
  826. $this->assertTrue($wrapper->access('edit', $account), 'Access to node granted.');
  827. $this->assertFalse($wrapper->status->access('edit', $account), 'Access for admin property denied.');
  828. $this->assertTrue($wrapper->status->access('edit', $account2), 'Access for admin property allowed for the admin.');
  829. // Test per property access with data.
  830. $wrapper = entity_metadata_wrapper('node', $node, array('bundle' => 'page'));
  831. $this->assertFalse($wrapper->status->access('edit', $account), 'Access for admin property denied.');
  832. $this->assertTrue($wrapper->status->access('edit', $account2), 'Access for admin property allowed for the admin.');
  833. // Test field level access.
  834. $this->assertTrue($wrapper->{$this->field_name}->access('view'), 'Field access granted.');
  835. // Create node owned by anonymous and test access() method on each of its
  836. // properties.
  837. $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => 0));
  838. $wrapper = entity_metadata_wrapper('node', $node->nid);
  839. foreach ($wrapper as $name => $property) {
  840. $property->access('view');
  841. }
  842. // Property access of entity references takes entity access into account.
  843. $node = $this->drupalCreateNode(array('type' => 'article'));
  844. $wrapper = entity_metadata_wrapper('node', $node);
  845. $unprivileged_user = $this->drupalCreateUser();
  846. $privileged_user = $this->drupalCreateUser(array('access user profiles'));
  847. $this->assertTrue($wrapper->author->access('view', $privileged_user));
  848. $this->assertFalse($wrapper->author->access('view', $unprivileged_user));
  849. // Ensure the same works with multiple entity references by testing the
  850. // $node->field_tags example.
  851. $privileged_user = $this->drupalCreateUser(array('administer taxonomy'));
  852. // Terms are view-able with access content, so make sure to remove this
  853. // permission first.
  854. user_role_revoke_permissions(DRUPAL_ANONYMOUS_RID, array('access content'));
  855. $unprivileged_user = drupal_anonymous_user();
  856. $this->assertTrue($wrapper->field_tags->access('view', $privileged_user), 'Privileged user has access.');
  857. $this->assertTrue($wrapper->field_tags->access('view', $unprivileged_user), 'Unprivileged user has access.');
  858. $this->assertTrue($wrapper->field_tags[0]->access('view', $privileged_user), 'Privileged user has access.');
  859. $this->assertFalse($wrapper->field_tags[0]->access('view', $unprivileged_user), 'Unprivileged user has no access.');
  860. }
  861. /**
  862. * Tests using a data structure with passed in metadata.
  863. */
  864. function testDataStructureWrapper() {
  865. $log_entry = array(
  866. 'type' => 'entity',
  867. 'message' => $this->randomName(8),
  868. 'variables' => array(),
  869. 'severity' => WATCHDOG_NOTICE,
  870. 'link' => '',
  871. 'user' => $GLOBALS['user'],
  872. );
  873. $info['property info'] = array(
  874. 'type' => array('type' => 'text', 'label' => 'The category to which this message belongs.'),
  875. 'message' => array('type' => 'text', 'label' => 'The log message.'),
  876. 'user' => array('type' => 'user', 'label' => 'The user causing the log entry.'),
  877. );
  878. $wrapper = entity_metadata_wrapper('log_entry', $log_entry, $info);
  879. $this->assertEqual($wrapper->user->name->value(), $GLOBALS['user']->name, 'Wrapped custom entity.');
  880. }
  881. /**
  882. * Tests using entity_property_query().
  883. */
  884. function testEntityQuery() {
  885. // Creat a test node.
  886. $title = '<b>Is it bold?<b>';
  887. $values[LANGUAGE_NONE][0] = array('value' => 'foo');
  888. $node = $this->drupalCreateNode(array($this->field_name => $values, 'title' => $title, 'uid' => $GLOBALS['user']->uid));
  889. $results = entity_property_query('node', 'title', $title);
  890. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given title.');
  891. $results = entity_property_query('node', $this->field_name, 'foo');
  892. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given field value.');
  893. $results = entity_property_query('node', $this->field_name, array('foo', 'bar'));
  894. $this->assertEqual($results, array($node->nid), 'Queried nodes with a list of possible values.');
  895. $results = entity_property_query('node', 'author', $GLOBALS['user']);
  896. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given auhtor.');
  897. // Create another test node and try querying for tags.
  898. $tag = entity_property_values_create_entity('taxonomy_term', array(
  899. 'name' => $this->randomName(),
  900. 'vocabulary' => 1,
  901. ))->save();
  902. $field_tag_value[LANGUAGE_NONE][0]['tid'] = $tag->getIdentifier();
  903. $node = $this->drupalCreateNode(array('type' => 'article', 'field_tags' => $field_tag_value));
  904. // Try query-ing with a single value.
  905. $results = entity_property_query('node', 'field_tags', $tag->getIdentifier());
  906. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given term id.');
  907. $results = entity_property_query('node', 'field_tags', $tag->value());
  908. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given term object.');
  909. // Try query-ing with a list of possible values.
  910. $results = entity_property_query('node', 'field_tags', array($tag->getIdentifier()));
  911. $this->assertEqual($results, array($node->nid), 'Queried nodes with a list of term ids.');
  912. }
  913. /**
  914. * Tests serializing data wrappers, in particular for EntityDrupalWrapper.
  915. */
  916. function testWrapperSerialization() {
  917. $node = $this->drupalCreateNode();
  918. $wrapper = entity_metadata_wrapper('node', $node);
  919. $this->assertTrue($wrapper->value() == $node, 'Data correctly wrapped.');
  920. // Test serializing and make sure only the node id is stored.
  921. $this->assertTrue(strpos(serialize($wrapper), $node->title) === FALSE, 'Node has been correctly serialized.');
  922. $this->assertEqual(unserialize(serialize($wrapper))->title->value(), $node->title, 'Serializing works right.');
  923. $wrapper2 = unserialize(serialize($wrapper));
  924. // Test serializing the unloaded wrapper.
  925. $this->assertEqual(unserialize(serialize($wrapper2))->title->value(), $node->title, 'Serializing works right.');
  926. // Test loading a not more existing node.
  927. $s = serialize($wrapper2);
  928. node_delete($node->nid);
  929. $this->assertFalse(node_load($node->nid), 'Node deleted.');
  930. $value = unserialize($s)->value();
  931. $this->assertNull($value, 'Tried to load not existing node.');
  932. }
  933. }
  934. /**
  935. * Tests basic entity_access() functionality for nodes.
  936. *
  937. * This code is a modified version of NodeAccessTestCase.
  938. *
  939. * @see NodeAccessTestCase
  940. */
  941. class EntityMetadataNodeAccessTestCase extends EntityWebTestCase {
  942. public static function getInfo() {
  943. return array(
  944. 'name' => 'Entity Metadata Node Access',
  945. 'description' => 'Test entity_access() for nodes',
  946. 'group' => 'Entity API',
  947. );
  948. }
  949. /**
  950. * Asserts node_access() correctly grants or denies access.
  951. */
  952. function assertNodeMetadataAccess($ops, $node, $account) {
  953. foreach ($ops as $op => $result) {
  954. $msg = t("entity_access() returns @result with operation '@op'.", array('@result' => $result ? 'TRUE' : 'FALSE', '@op' => $op));
  955. $access = entity_access($op, 'node', $node, $account);
  956. $this->assertEqual($result, $access, $msg);
  957. }
  958. }
  959. function setUp() {
  960. parent::setUp('entity', 'node');
  961. // Clear permissions for authenticated users.
  962. db_delete('role_permission')
  963. ->condition('rid', DRUPAL_AUTHENTICATED_RID)
  964. ->execute();
  965. }
  966. /**
  967. * Runs basic tests for entity_access() function.
  968. */
  969. function testNodeMetadataAccess() {
  970. // Author user.
  971. $node_author_account = $this->drupalCreateUser(array());
  972. // Make a node object.
  973. $settings = array(
  974. 'uid' => $node_author_account->uid,
  975. 'type' => 'page',
  976. 'title' => 'Node ' . $this->randomName(32),
  977. );
  978. $node = $this->drupalCreateNode($settings);
  979. // Ensures user without 'access content' permission can do nothing.
  980. $web_user1 = $this->drupalCreateUser(array('create page content', 'edit any page content', 'delete any page content'));
  981. $this->assertNodeMetadataAccess(array('create' => FALSE, 'view' => FALSE, 'update' => FALSE, 'delete' => FALSE), $node, $web_user1);
  982. // Ensures user with 'bypass node access' permission can do everything.
  983. $web_user2 = $this->drupalCreateUser(array('bypass node access'));
  984. $this->assertNodeMetadataAccess(array('create' => TRUE, 'view' => TRUE, 'update' => TRUE, 'delete' => TRUE), $node, $web_user2);
  985. // User cannot 'view own unpublished content'.
  986. $web_user3 = $this->drupalCreateUser(array('access content'));
  987. // Create an unpublished node.
  988. $settings = array('type' => 'page', 'status' => 0, 'uid' => $web_user3->uid);
  989. $node_unpublished = $this->drupalCreateNode($settings);
  990. $this->assertNodeMetadataAccess(array('view' => FALSE), $node_unpublished, $web_user3);
  991. // User cannot create content without permission.
  992. $this->assertNodeMetadataAccess(array('create' => FALSE), $node, $web_user3);
  993. // User can 'view own unpublished content', but another user cannot.
  994. $web_user4 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
  995. $web_user5 = $this->drupalCreateUser(array('access content', 'view own unpublished content'));
  996. $node4 = $this->drupalCreateNode(array('status' => 0, 'uid' => $web_user4->uid));
  997. $this->assertNodeMetadataAccess(array('view' => TRUE, 'update' => FALSE), $node4, $web_user4);
  998. $this->assertNodeMetadataAccess(array('view' => FALSE), $node4, $web_user5);
  999. // Tests the default access provided for a published node.
  1000. $node5 = $this->drupalCreateNode();
  1001. $this->assertNodeMetadataAccess(array('view' => TRUE, 'update' => FALSE, 'delete' => FALSE, 'create' => FALSE), $node5, $web_user3);
  1002. }
  1003. }
  1004. /**
  1005. * Test user permissions for node creation.
  1006. */
  1007. class EntityMetadataNodeCreateAccessTestCase extends EntityWebTestCase {
  1008. public static function getInfo() {
  1009. return array(
  1010. 'name' => 'Entity Metadata Node Create Access',
  1011. 'description' => 'Test entity_access() for nodes',
  1012. 'group' => 'Entity API',
  1013. );
  1014. }
  1015. function setUp() {
  1016. parent::setUp('entity', 'node');
  1017. }
  1018. /**
  1019. * Addresses the special case of 'create' access for nodes.
  1020. */
  1021. public function testNodeMetadataCreateAccess() {
  1022. // Create some users. One with super-powers, one with create perms,
  1023. // and one with no perms, and a different one to author the node.
  1024. $admin_account = $this->drupalCreateUser(array(
  1025. 'bypass node access',
  1026. ));
  1027. $creator_account = $this->drupalCreateUser(array(
  1028. 'create page content',
  1029. ));
  1030. $auth_only_account = $this->drupalCreateUser(array());
  1031. $node_author_account = $this->drupalCreateUser(array());
  1032. // Make a node object with Entity API (contrib)
  1033. $settings = array(
  1034. 'uid' => $node_author_account->uid,
  1035. 'type' => 'page',
  1036. 'title' => $this->randomName(32),
  1037. 'body' => array(LANGUAGE_NONE => array(array($this->randomName(64)))),
  1038. );
  1039. $node = entity_create('node', $settings);
  1040. // Test the populated wrapper.
  1041. $wrapper = entity_metadata_wrapper('node', $node);
  1042. $this->assertTrue($wrapper->entityAccess('create', $admin_account), 'Create access allowed for ADMIN, for populated wrapper.');
  1043. $this->assertTrue($wrapper->entityAccess('create', $creator_account), 'Create access allowed for CREATOR, for populated wrapper.');
  1044. $this->assertFalse($wrapper->entityAccess('create', $auth_only_account), 'Create access denied for USER, for populated wrapper.');
  1045. // Test entity_acces().
  1046. $this->assertTrue(entity_access('create', 'node', $node, $admin_account), 'Create access allowed for ADMIN, for entity_access().');
  1047. $this->assertTrue(entity_access('create', 'node', $node, $creator_account), 'Create access allowed for CREATOR, for entity_access().');
  1048. $this->assertFalse(entity_access('create', 'node', $node, $auth_only_account), 'Create access denied for USER, for entity_access().');
  1049. }
  1050. }
  1051. /**
  1052. * Tests user permissions for node revisions.
  1053. *
  1054. * Based almost entirely on NodeRevisionPermissionsTestCase.
  1055. */
  1056. class EntityMetadataNodeRevisionAccessTestCase extends DrupalWebTestCase {
  1057. protected $node_revisions = array();
  1058. protected $accounts = array();
  1059. // Map revision permission names to node revision access ops.
  1060. protected $map = array(
  1061. 'view' => 'view revisions',
  1062. 'update' => 'revert revisions',
  1063. 'delete' => 'delete revisions',
  1064. );
  1065. public static function getInfo() {
  1066. return array(
  1067. 'name' => 'Entity Metadata Node Revision Access',
  1068. 'description' => 'Tests user permissions for node revision operations.',
  1069. 'group' => 'Entity API',
  1070. );
  1071. }
  1072. function setUp() {
  1073. parent::setUp('entity', 'node');
  1074. // Create a node with several revisions.
  1075. $node = $this->drupalCreateNode();
  1076. $this->node_revisions[] = $node;
  1077. for ($i = 0; $i < 3; $i++) {
  1078. // Create a revision for the same nid and settings with a random log.
  1079. $revision = node_load($node->nid);
  1080. $revision->revision = 1;
  1081. $revision->log = $this->randomName(32);
  1082. node_save($revision);
  1083. $this->node_revisions[] = node_load($revision->nid);
  1084. }
  1085. // Create three users, one with each revision permission.
  1086. foreach ($this->map as $op => $permission) {
  1087. // Create the user.
  1088. $account = $this->drupalCreateUser(
  1089. array(
  1090. 'access content',
  1091. 'edit any page content',
  1092. 'delete any page content',
  1093. $permission,
  1094. )
  1095. );
  1096. $account->op = $op;
  1097. $this->accounts[] = $account;
  1098. }
  1099. // Create an admin account (returns TRUE for all revision permissions).
  1100. $admin_account = $this->drupalCreateUser(array('access content', 'administer nodes'));
  1101. $admin_account->is_admin = TRUE;
  1102. $this->accounts['admin'] = $admin_account;
  1103. // Create a normal account (returns FALSE for all revision permissions).
  1104. $normal_account = $this->drupalCreateUser();
  1105. $normal_account->op = FALSE;
  1106. $this->accounts[] = $normal_account;
  1107. }
  1108. /**
  1109. * Tests the entity_access() function for revisions.
  1110. */
  1111. function testNodeRevisionAccess() {
  1112. // $node_revisions[1] won't be the latest revision.
  1113. $revision = $this->node_revisions[1];
  1114. $parameters = array(
  1115. 'op' => array_keys($this->map),
  1116. 'account' => $this->accounts,
  1117. );
  1118. $permutations = $this->generatePermutations($parameters);
  1119. $entity_type = 'node';
  1120. foreach ($permutations as $case) {
  1121. if (!empty($case['account']->is_admin) || $case['op'] == $case['account']->op) {
  1122. $access = entity_access($case['op'], $entity_type, $revision, $case['account']);
  1123. $this->assertTrue($access, "{$this->map[$case['op']]} granted on $entity_type.");
  1124. }
  1125. else {
  1126. $access = entity_access($case['op'], $entity_type, $revision, $case['account']);
  1127. $this->assertFalse($access, "{$this->map[$case['op']]} NOT granted on $entity_type.");
  1128. }
  1129. }
  1130. }
  1131. }
  1132. /**
  1133. * Tests basic entity_access() functionality for taxonomy terms.
  1134. */
  1135. class EntityMetadataTaxonomyAccessTestCase extends EntityWebTestCase {
  1136. public static function getInfo() {
  1137. return array(
  1138. 'name' => 'Entity Metadata Taxonomy Access',
  1139. 'description' => 'Test entity_access() for taxonomy terms',
  1140. 'group' => 'Entity API',
  1141. );
  1142. }
  1143. /**
  1144. * Asserts entity_access() correctly grants or denies access.
  1145. */
  1146. function assertTaxonomyMetadataAccess($ops, $term, $account) {
  1147. foreach ($ops as $op => $result) {
  1148. $msg = t("entity_access() returns @result with operation '@op'.", array('@result' => $result ? 'TRUE' : 'FALSE', '@op' => $op));
  1149. $access = entity_access($op, 'taxonomy_term', $term, $account);
  1150. $this->assertEqual($result, $access, $msg);
  1151. }
  1152. }
  1153. /**
  1154. * @inheritdoc
  1155. */
  1156. function setUp() {
  1157. parent::setUp('entity', 'taxonomy');
  1158. // Clear permissions for authenticated users.
  1159. db_delete('role_permission')
  1160. ->condition('rid', DRUPAL_AUTHENTICATED_RID)
  1161. ->execute();
  1162. }
  1163. /**
  1164. * Runs basic tests for entity_access() function.
  1165. */
  1166. function testTaxonomyMetadataAccess() {
  1167. $vocab = $this->createVocabulary();
  1168. $term = entity_property_values_create_entity('taxonomy_term', array(
  1169. 'name' => $this->randomName(),
  1170. 'vocabulary' => $vocab,
  1171. ))->save()->value();
  1172. // Clear permissions static cache to get new taxonomy permissions.
  1173. drupal_static_reset('checkPermissions');
  1174. // Check assignment of view permissions.
  1175. $user1 = $this->drupalCreateUser(array('access content'));
  1176. $this->assertTaxonomyMetadataAccess(array('create' => FALSE, 'view' => TRUE, 'update' => FALSE, 'delete' => FALSE), $term, $user1);
  1177. // Check assignment of edit permissions.
  1178. $user2 = $this->drupalCreateUser(array('edit terms in ' . $vocab->vid));
  1179. $this->assertTaxonomyMetadataAccess(array('create' => FALSE, 'view' => FALSE, 'update' => TRUE, 'delete' => FALSE), $term, $user2);
  1180. // Check assignment of delete permissions.
  1181. $user3 = $this->drupalCreateUser(array('delete terms in ' . $vocab->vid));
  1182. $this->assertTaxonomyMetadataAccess(array('create' => FALSE, 'view' => FALSE, 'update' => FALSE, 'delete' => TRUE), $term, $user3);
  1183. // Check assignment of view, edit, delete permissions.
  1184. $user4 = $this->drupalCreateUser(array('access content', 'edit terms in ' . $vocab->vid, 'delete terms in ' . $vocab->vid));
  1185. $this->assertTaxonomyMetadataAccess(array('create' => FALSE, 'view' => TRUE, 'update' => TRUE, 'delete' => TRUE), $term, $user4);
  1186. // Check assignment of administration permissions.
  1187. $user5 = $this->drupalCreateUser(array('administer taxonomy'));
  1188. $this->assertTaxonomyMetadataAccess(array('create' => TRUE, 'view' => TRUE, 'update' => TRUE, 'delete' => TRUE), $term, $user5);
  1189. }
  1190. }
  1191. /**
  1192. * Tests provided entity property info of the core modules.
  1193. */
  1194. class EntityTokenTestCase extends EntityWebTestCase {
  1195. public static function getInfo() {
  1196. return array(
  1197. 'name' => 'Entity tokens',
  1198. 'description' => 'Tests provided tokens for entity properties.',
  1199. 'group' => 'Entity API',
  1200. );
  1201. }
  1202. function setUp() {
  1203. parent::setUp('entity_token');
  1204. }
  1205. /**
  1206. * Tests whether token support is basically working.
  1207. */
  1208. function testTokenSupport() {
  1209. // Test basic tokens.
  1210. $node = $this->drupalCreateNode(array('sticky' => TRUE, 'promote' => FALSE));
  1211. $text = "Sticky: [node:sticky] Promote: [node:promote] User: [site:current-user:name]";
  1212. $true = t('true');
  1213. $false = t('false');
  1214. $user_name = $GLOBALS['user']->name;
  1215. $target = "Sticky: $true Promote: $false User: $user_name";
  1216. $replace = token_replace($text, array('node' => $node));
  1217. $this->assertEqual($replace, $target, 'Provided tokens basically work.');
  1218. // Test multiple-value tokens using the tags field of articles.
  1219. for ($i = 0; $i < 4; $i++) {
  1220. $tags[$i] = entity_property_values_create_entity('taxonomy_term', array(
  1221. 'name' => $this->randomName(),
  1222. 'vocabulary' => 1,
  1223. ))->save();
  1224. $field_value[LANGUAGE_NONE][$i]['tid'] = $tags[$i]->getIdentifier();
  1225. $labels[$i] = $tags[$i]->label();
  1226. }
  1227. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', 'field_tags' => $field_value));
  1228. $text = "Tags: [node:field-tags] First: [node:field-tags:0] 2nd name: [node:field-tags:1:name] 1st vocab [node:field-tags:0:vocabulary]";
  1229. $tag_labels = implode(', ', $labels);
  1230. $target = "Tags: $tag_labels First: $labels[0] 2nd name: $labels[1] 1st vocab {$tags[0]->vocabulary->label()}";
  1231. $replace = token_replace($text, array('node' => $node));
  1232. $this->assertEqual($replace, $target, 'Multiple-value token replacements have been replaced.');
  1233. // Make sure not existing values are not handled.
  1234. $replace = token_replace("[node:field-tags:43]", array('node' => $node));
  1235. $this->assertEqual($replace, "[node:field-tags:43]", 'Not existing values are not replaced.');
  1236. // Test data-structure tokens like [site:current-page:url].
  1237. $replace = token_replace("[site:current-page:url]", array());
  1238. $this->assertEqual($replace, $GLOBALS['base_root'] . request_uri(), 'Token replacements of data structure properties replaced.');
  1239. // Test chaining of data-structure tokens using an image-field.
  1240. $file = $this->createFile('image');
  1241. $node = $this->drupalCreateNode(array('type' => 'article'));
  1242. $wrapper = entity_metadata_wrapper('node', $node);
  1243. $wrapper->field_image = array('fid' => $file->fid);
  1244. $replace = token_replace("[node:field-image:file:name]", array('node' => $node));
  1245. $this->assertEqual($replace, $wrapper->field_image->file->name->value(), 'Token replacements of an image field have been replaced.');
  1246. }
  1247. }
  1248. /**
  1249. * Tests provided entity property info of the core modules.
  1250. */
  1251. class EntityMetadataIntegrationTestCase extends EntityWebTestCase {
  1252. public static function getInfo() {
  1253. return array(
  1254. 'name' => 'Property info core integration',
  1255. 'description' => 'Tests using metadata wrapper for drupal core.',
  1256. 'group' => 'Entity API',
  1257. );
  1258. }
  1259. function setUp() {
  1260. parent::setUp('entity', 'book', 'statistics', 'locale');
  1261. }
  1262. protected function assertException($wrapper, $name, $text = NULL) {
  1263. $this->assertTrue(isset($wrapper->$name), 'Property wrapper ' . check_plain($name) . ' exists.');
  1264. $text = isset($text) ? $text : 'Getting the not existing property ' . $name . ' throws exception.';
  1265. try {
  1266. $wrapper->$name->value();
  1267. $this->fail($text);
  1268. }
  1269. catch (EntityMetadataWrapperException $e) {
  1270. $this->pass($text);
  1271. }
  1272. }
  1273. protected function assertEmpty($wrapper, $name) {
  1274. $this->assertTrue(isset($wrapper->$name), 'Property ' . check_plain($name) . ' exists.');
  1275. $this->assertTrue($wrapper->$name->value() === NULL, 'Property ' . check_plain($name) . ' is empty.');
  1276. }
  1277. protected function assertEmptyArray($wrapper, $name) {
  1278. $this->assertTrue(isset($wrapper->$name), 'Property ' . check_plain($name) . ' exists.');
  1279. $this->assertTrue($wrapper->$name->value() === array(), 'Property ' . check_plain($name) . ' is an empty array.');
  1280. }
  1281. protected function assertValue($wrapper, $key) {
  1282. $this->assertTrue($wrapper->$key->value() !== NULL, check_plain($key) . ' property returned.');
  1283. $info = $wrapper->$key->info();
  1284. if (!empty($info['raw getter callback'])) {
  1285. // Also test getting the raw value
  1286. $this->assertTrue($wrapper->$key->raw() !== NULL, check_plain($key) . ' raw value returned.');
  1287. }
  1288. }
  1289. /**
  1290. * Test book module integration.
  1291. */
  1292. function testBookModule() {
  1293. $title = 'Book 1';
  1294. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'book', 'book' => array('bid' => 'new')));
  1295. $book = array('bid' => $node->nid, 'plid' => $node->book['mlid']);
  1296. $node2 = $this->drupalCreateNode(array('type' => 'book', 'book' => $book));
  1297. $node3 = $this->drupalCreateNode(array('type' => 'page'));
  1298. $node4 = $this->drupalCreateNode(array('type' => 'book', 'book' => array('bid' => 0, 'plid' => -1)));
  1299. // Test whether the properties work.
  1300. $wrapper = entity_metadata_wrapper('node', $node2);
  1301. $this->assertEqual($title, $wrapper->book->title->value(), "Book title returned.");
  1302. $this->assertEqual(array($node->nid), $wrapper->book_ancestors->value(array('identifier' => TRUE)), "Book ancestors returned.");
  1303. $this->assertEqual($node->nid, $wrapper->book->nid->value(), "Book id returned.");
  1304. // Try using book properties for no book nodes.
  1305. $wrapper = entity_metadata_wrapper('node', $node3);
  1306. $this->assertEmpty($wrapper, 'book');
  1307. $this->assertEmptyArray($wrapper, 'book_ancestors');
  1308. // Test a book node which is not contained in a hierarchy.
  1309. $wrapper = entity_metadata_wrapper('node', $node4);
  1310. $this->assertEmptyArray($wrapper, 'book_ancestors');
  1311. }
  1312. /**
  1313. * Test properties of a comment.
  1314. */
  1315. function testComments() {
  1316. $title = 'Node 1';
  1317. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'page'));
  1318. $author = $this->drupalCreateUser(array('access comments', 'post comments', 'edit own comments'));
  1319. $comment = (object)array(
  1320. 'subject' => 'topic',
  1321. 'nid' => $node->nid,
  1322. 'uid' => $author->uid,
  1323. 'cid' => FALSE,
  1324. 'pid' => 0,
  1325. 'homepage' => '',
  1326. 'language' => LANGUAGE_NONE,
  1327. 'hostname' => ip_address(),
  1328. );
  1329. $comment->comment_body[LANGUAGE_NONE][0] = array('value' => 'text', 'format' => 0);
  1330. comment_save($comment);
  1331. $wrapper = entity_metadata_wrapper('comment', $comment);
  1332. foreach ($wrapper as $key => $value) {
  1333. if ($key != 'parent') {
  1334. $this->assertValue($wrapper, $key);
  1335. }
  1336. }
  1337. $this->assertEmpty($wrapper, 'parent');
  1338. // Test comment entity access.
  1339. $admin_user = $this->drupalCreateUser(array('access comments', 'administer comments', 'access user profiles'));
  1340. // Also grant access to view user accounts to test the comment author
  1341. // property.
  1342. $unprivileged_user = $this->drupalCreateUser(array('access comments', 'access user profiles'));
  1343. // Published comments can be viewed and edited by the author.
  1344. $this->assertTrue($wrapper->access('view', $author), 'Comment author is allowed to view the published comment.');
  1345. $this->assertTrue($wrapper->access('edit', $author), 'Comment author is allowed to edit the published comment.');
  1346. // We cannot use $wrapper->access('delete') here because it only understands
  1347. // view and edit.
  1348. $this->assertFalse(entity_access('delete', 'comment', $comment, $author), 'Comment author is not allowed to delete the published comment.');
  1349. // Administrators can do anything with published comments.
  1350. $this->assertTrue($wrapper->access('view', $admin_user), 'Comment administrator is allowed to view the published comment.');
  1351. $this->assertTrue($wrapper->access('edit', $admin_user), 'Comment administrator is allowed to edit the published comment.');
  1352. $this->assertTrue(entity_access('delete', 'comment', $comment, $admin_user), 'Comment administrator is allowed to delete the published comment.');
  1353. // Unpriviledged users can only view the published comment.
  1354. $this->assertTrue($wrapper->access('view', $unprivileged_user), 'Unprivileged user is allowed to view the published comment.');
  1355. $this->assertFalse($wrapper->access('edit', $unprivileged_user), 'Unprivileged user is not allowed to edit the published comment.');
  1356. $this->assertFalse(entity_access('delete', 'comment', $comment, $unprivileged_user), 'Unprivileged user is not allowed to delete the published comment.');
  1357. // Test property view access.
  1358. $view_access = array('name', 'homepage', 'subject', 'created', 'author', 'node', 'parent', 'url', 'edit_url');
  1359. foreach ($view_access as $property_name) {
  1360. $this->assertTrue($wrapper->{$property_name}->access('view', $unprivileged_user), "Unpriviledged user can view the $property_name property.");
  1361. }
  1362. $view_denied = array('hostname', 'mail', 'status');
  1363. foreach ($view_denied as $property_name) {
  1364. $this->assertFalse($wrapper->{$property_name}->access('view', $unprivileged_user), "Unpriviledged user can not view the $property_name property.");
  1365. $this->assertTrue($wrapper->{$property_name}->access('view', $admin_user), "Admin user can view the $property_name property.");
  1366. }
  1367. // The author is allowed to edit the comment subject if they have the
  1368. // 'edit own comments' permission.
  1369. $this->assertTrue($wrapper->subject->access('edit', $author), "Author can edit the subject property.");
  1370. $this->assertFalse($wrapper->subject->access('edit', $unprivileged_user), "Unpriviledged user cannot edit the subject property.");
  1371. $this->assertTrue($wrapper->subject->access('edit', $admin_user), "Admin user can edit the subject property.");
  1372. $edit_denied = array('hostname', 'mail', 'status', 'name', 'homepage', 'created', 'parent', 'node', 'author');
  1373. foreach ($edit_denied as $property_name) {
  1374. $this->assertFalse($wrapper->{$property_name}->access('edit', $author), "Author cannot edit the $property_name property.");
  1375. $this->assertTrue($wrapper->{$property_name}->access('edit', $admin_user), "Admin user can edit the $property_name property.");
  1376. }
  1377. // Test access to unpublished comments.
  1378. $comment->status = COMMENT_NOT_PUBLISHED;
  1379. comment_save($comment);
  1380. // Unpublished comments cannot be accessed by the author.
  1381. $this->assertFalse($wrapper->access('view', $author), 'Comment author is not allowed to view the unpublished comment.');
  1382. $this->assertFalse($wrapper->access('edit', $author), 'Comment author is not allowed to edit the unpublished comment.');
  1383. $this->assertFalse(entity_access('delete', 'comment', $comment, $author), 'Comment author is not allowed to delete the unpublished comment.');
  1384. // Administrators can do anything with unpublished comments.
  1385. $this->assertTrue($wrapper->access('view', $admin_user), 'Comment administrator is allowed to view the unpublished comment.');
  1386. $this->assertTrue($wrapper->access('edit', $admin_user), 'Comment administrator is allowed to edit the unpublished comment.');
  1387. $this->assertTrue(entity_access('delete', 'comment', $comment, $admin_user), 'Comment administrator is allowed to delete the unpublished comment.');
  1388. // Unpriviledged users cannot access unpublished comments.
  1389. $this->assertFalse($wrapper->access('view', $unprivileged_user), 'Unprivileged user is not allowed to view the unpublished comment.');
  1390. $this->assertFalse($wrapper->access('edit', $unprivileged_user), 'Unprivileged user is not allowed to edit the unpublished comment.');
  1391. $this->assertFalse(entity_access('delete', 'comment', $comment, $unprivileged_user), 'Unprivileged user is not allowed to delete the unpublished comment.');
  1392. }
  1393. /**
  1394. * Test all properties of a node.
  1395. */
  1396. function testNodeProperties() {
  1397. $title = 'Book 1';
  1398. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'page'));
  1399. $wrapper = entity_metadata_wrapper('node', $node);
  1400. foreach ($wrapper as $key => $value) {
  1401. if ($key != 'book' && $key != 'book_ancestors' && $key != 'source' && $key != 'last_view') {
  1402. $this->assertValue($wrapper, $key);
  1403. }
  1404. }
  1405. $this->assertEmpty($wrapper, 'book');
  1406. $this->assertEmptyArray($wrapper, 'book_ancestors');
  1407. $this->assertEmpty($wrapper, 'source');
  1408. $this->assertException($wrapper->source, 'title');
  1409. $this->assertEmpty($wrapper, 'last_view');
  1410. // Test statistics module integration access.
  1411. $unpriviledged_user = $this->drupalCreateUser(array('access content'));
  1412. $this->assertTrue($wrapper->access('view', $unpriviledged_user), 'Unpriviledged user can view the node.');
  1413. $this->assertFalse($wrapper->access('edit', $unpriviledged_user), 'Unpriviledged user can not edit the node.');
  1414. $count_access_user = $this->drupalCreateUser(array('view post access counter'));
  1415. $admin_user = $this->drupalCreateUser(array('access content', 'view post access counter', 'access statistics'));
  1416. $this->assertFalse($wrapper->views->access('view', $unpriviledged_user), "Unpriviledged user cannot view the statistics counter property.");
  1417. $this->assertTrue($wrapper->views->access('view', $count_access_user), "Count access user can view the statistics counter property.");
  1418. $this->assertTrue($wrapper->views->access('view', $admin_user), "Admin user can view the statistics counter property.");
  1419. $admin_properties = array('day_views', 'last_view');
  1420. foreach ($admin_properties as $property_name) {
  1421. $this->assertFalse($wrapper->{$property_name}->access('view', $unpriviledged_user), "Unpriviledged user cannot view the $property_name property.");
  1422. $this->assertFalse($wrapper->{$property_name}->access('view', $count_access_user), "Count access user cannot view the $property_name property.");
  1423. $this->assertTrue($wrapper->{$property_name}->access('view', $admin_user), "Admin user can view the $property_name property.");
  1424. }
  1425. }
  1426. /**
  1427. * Tests properties provided by the taxonomy module.
  1428. */
  1429. function testTaxonomyProperties() {
  1430. $vocab = $this->createVocabulary();
  1431. $term_parent = entity_property_values_create_entity('taxonomy_term', array(
  1432. 'name' => $this->randomName(),
  1433. 'vocabulary' => $vocab,
  1434. ))->save()->value();
  1435. $term_parent2 = entity_property_values_create_entity('taxonomy_term', array(
  1436. 'name' => $this->randomName(),
  1437. 'vocabulary' => $vocab,
  1438. ))->save()->value();
  1439. $term = entity_property_values_create_entity('taxonomy_term', array(
  1440. 'name' => $this->randomName(),
  1441. 'vocabulary' => $vocab,
  1442. 'description' => $this->randomString(),
  1443. 'weight' => mt_rand(0, 10),
  1444. 'parent' => array($term_parent->tid),
  1445. ))->save()->value();
  1446. $wrapper = entity_metadata_wrapper('taxonomy_term', $term);
  1447. foreach ($wrapper as $key => $value) {
  1448. $this->assertValue($wrapper, $key);
  1449. }
  1450. // Test setting another parent using the full object.
  1451. $wrapper->parent[] = $term_parent2;
  1452. $this->assertEqual($wrapper->parent[1]->getIdentifier(), $term_parent2->tid, 'Term parent added.');
  1453. $parents = $wrapper->parent->value();
  1454. $tids = $term_parent->tid . ':' . $term_parent2->tid;
  1455. $this->assertEqual($parents[0]->tid . ':' . $parents[1]->tid, $tids, 'Parents returned.');
  1456. $this->assertEqual(implode(':', $wrapper->parent->value(array('identifier' => TRUE))), $tids, 'Parent ids returned.');
  1457. // Test vocabulary.
  1458. foreach ($wrapper->vocabulary as $key => $value) {
  1459. $this->assertValue($wrapper->vocabulary, $key);
  1460. }
  1461. // Test field integration.
  1462. $tags[LANGUAGE_NONE][0]['tid'] = $term->tid;
  1463. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', 'field_tags' => $tags));
  1464. $wrapper = entity_metadata_wrapper('node', $node);
  1465. $this->assertEqual($wrapper->field_tags[0]->name->value(), $term->name, 'Get an associated tag of a node with the wrapper.');
  1466. $wrapper->field_tags[1] = $term_parent;
  1467. $tags = $wrapper->field_tags->value();
  1468. $this->assertEqual($tags[1]->tid, $term_parent->tid, 'Associated a new tag with a node.');
  1469. $this->assertEqual($tags[0]->tid, $term->tid, 'Previsous set association kept.');
  1470. // Test getting a list of identifiers.
  1471. $tags = $wrapper->field_tags->value(array('identifier' => TRUE));
  1472. $this->assertEqual($tags, array($term->tid, $term_parent->tid), 'List of referenced term identifiers returned.');
  1473. // Test setting tags by using ids.
  1474. $wrapper->field_tags->set(array(2));
  1475. $this->assertEqual($wrapper->field_tags[0]->tid->value(), 2, 'Specified tags by a list of term ids.');
  1476. // Test unsetting all tags.
  1477. $wrapper->field_tags = NULL;
  1478. $this->assertFalse($wrapper->field_tags->value(), 'Unset all tags from a node.');
  1479. // Test setting entity references to NULL.
  1480. // Create a taxonomy term field for that purpose.
  1481. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  1482. $field = array('field_name' => $field_name, 'type' => 'taxonomy_term_reference', 'cardinality' => 1);
  1483. $field = field_create_field($field);
  1484. $field_id = $field['id'];
  1485. $field_instance = array(
  1486. 'field_name' => $field_name,
  1487. 'entity_type' => 'node',
  1488. 'bundle' => 'article',
  1489. 'label' => $this->randomName() . '_label',
  1490. 'description' => $this->randomName() . '_description',
  1491. 'weight' => mt_rand(0, 127),
  1492. 'widget' => array(
  1493. 'type' => 'options_select',
  1494. 'label' => 'Test term field',
  1495. )
  1496. );
  1497. field_create_instance($field_instance);
  1498. $term_field[LANGUAGE_NONE][0]['tid'] = $term->tid;
  1499. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', $field_name => $term_field));
  1500. $wrapper = entity_metadata_wrapper('node', $node);
  1501. $wrapper->$field_name->set(NULL);
  1502. $termref = $wrapper->$field_name->value();
  1503. $this->assertNull($termref, 'Unset of a term reference successful.');
  1504. }
  1505. /**
  1506. * Test all properties of a user.
  1507. */
  1508. function testUserProperties() {
  1509. $account = $this->drupalCreateUser(array('access user profiles', 'change own username'));
  1510. $account->login = REQUEST_TIME;
  1511. $account->access = REQUEST_TIME;
  1512. $wrapper = entity_metadata_wrapper('user', $account);
  1513. foreach ($wrapper as $key => $value) {
  1514. $this->assertValue($wrapper, $key);
  1515. }
  1516. // Test property view access.
  1517. $unpriviledged_user = $this->drupalCreateUser(array('access user profiles'));
  1518. $admin_user = $this->drupalCreateUser(array('administer users'));
  1519. $this->assertTrue($wrapper->access('view', $unpriviledged_user), 'Unpriviledged account can view the user.');
  1520. $this->assertFalse($wrapper->access('edit', $unpriviledged_user), 'Unpriviledged account can not edit the user.');
  1521. $view_access = array('name', 'url', 'edit_url', 'created');
  1522. foreach ($view_access as $property_name) {
  1523. $this->assertTrue($wrapper->{$property_name}->access('view', $unpriviledged_user), "Unpriviledged user can view the $property_name property.");
  1524. }
  1525. $view_denied = array('mail', 'last_access', 'last_login', 'roles', 'status', 'theme');
  1526. foreach ($view_denied as $property_name) {
  1527. $this->assertFalse($wrapper->{$property_name}->access('view', $unpriviledged_user), "Unpriviledged user can not view the $property_name property.");
  1528. $this->assertTrue($wrapper->{$property_name}->access('view', $admin_user), "Admin user can view the $property_name property.");
  1529. }
  1530. // Test property edit access.
  1531. $edit_own_allowed = array('name', 'mail');
  1532. foreach ($edit_own_allowed as $property_name) {
  1533. $this->assertTrue($wrapper->{$property_name}->access('edit', $account), "Account owner can edit the $property_name property.");
  1534. }
  1535. $this->assertTrue($wrapper->roles->access('view', $account), "Account owner can view their own roles.");
  1536. $edit_denied = array('last_access', 'last_login', 'created', 'roles', 'status', 'theme');
  1537. foreach ($edit_denied as $property_name) {
  1538. $this->assertFalse($wrapper->{$property_name}->access('edit', $account), "Account owner cannot edit the $property_name property.");
  1539. $this->assertTrue($wrapper->{$property_name}->access('edit', $admin_user), "Admin user can edit the $property_name property.");
  1540. }
  1541. }
  1542. /**
  1543. * Test properties provided by system module.
  1544. */
  1545. function testSystemProperties() {
  1546. $wrapper = entity_metadata_site_wrapper();
  1547. foreach ($wrapper as $key => $value) {
  1548. $this->assertValue($wrapper, $key);
  1549. }
  1550. // Test page request related properties.
  1551. foreach ($wrapper->current_page as $key => $value) {
  1552. $this->assertValue($wrapper->current_page, $key);
  1553. }
  1554. // Test files.
  1555. $file = $this->createFile();
  1556. $wrapper = entity_metadata_wrapper('file', $file);
  1557. foreach ($wrapper as $key => $value) {
  1558. $this->assertValue($wrapper, $key);
  1559. }
  1560. }
  1561. /**
  1562. * Runs some generic tests on each entity.
  1563. */
  1564. function testCRUDfunctions() {
  1565. $info = entity_get_info();
  1566. foreach ($info as $entity_type => $entity_info) {
  1567. // Test using access callback.
  1568. entity_access('view', $entity_type);
  1569. entity_access('update', $entity_type);
  1570. entity_access('create', $entity_type);
  1571. entity_access('delete', $entity_type);
  1572. // Test creating the entity.
  1573. if (!isset($entity_info['creation callback'])) {
  1574. continue;
  1575. }
  1576. // Populate $values with all values that are setable. They will be set
  1577. // with an metadata wrapper, so we also test setting that way.
  1578. $values = array();
  1579. foreach (entity_metadata_wrapper($entity_type) as $name => $wrapper) {
  1580. $info = $wrapper->info();
  1581. if (!empty($info['setter callback'])) {
  1582. $values[$name] = $this->createValue($wrapper);
  1583. }
  1584. }
  1585. $entity = entity_property_values_create_entity($entity_type, $values)->value();
  1586. $this->assertTrue($entity, "Created $entity_type and set all setable values.");
  1587. // Save the new entity.
  1588. $return = entity_save($entity_type, $entity);
  1589. if ($return === FALSE) {
  1590. continue; // No support for saving.
  1591. }
  1592. $id = entity_metadata_wrapper($entity_type, $entity)->getIdentifier();
  1593. $this->assertTrue($id, "$entity_type has been successfully saved.");
  1594. // And delete it.
  1595. $return = entity_delete($entity_type, $id);
  1596. if ($return === FALSE) {
  1597. continue; // No support for deleting.
  1598. }
  1599. $return = entity_load_single($entity_type, $id);
  1600. $this->assertFalse($return, "$entity_type has been successfully deleted.");
  1601. }
  1602. }
  1603. /**
  1604. * Test making use of a text fields.
  1605. */
  1606. function testTextFields() {
  1607. // Create a simple text field without text processing.
  1608. $field = array(
  1609. 'field_name' => 'field_text',
  1610. 'type' => 'text',
  1611. 'cardinality' => 2,
  1612. );
  1613. field_create_field($field);
  1614. $instance = array(
  1615. 'field_name' => 'field_text',
  1616. 'entity_type' => 'node',
  1617. 'label' => 'test',
  1618. 'bundle' => 'article',
  1619. 'widget' => array(
  1620. 'type' => 'text_textfield',
  1621. 'weight' => -1,
  1622. ),
  1623. );
  1624. field_create_instance($instance);
  1625. $node = $this->drupalCreateNode(array('type' => 'article'));
  1626. $wrapper = entity_metadata_wrapper('node', $node);
  1627. $wrapper->field_text[0] = 'the text';
  1628. // Try saving the node and make sure the information is still there after
  1629. // loading the node again, thus the correct data structure has been written.
  1630. node_save($node);
  1631. $node = node_load($node->nid, NULL, TRUE);
  1632. $wrapper = entity_metadata_wrapper('node', $node);
  1633. $this->assertEqual('the text', $wrapper->field_text[0]->value(), 'Text has been specified.');
  1634. // Now activate text processing.
  1635. $instance['settings']['text_processing'] = 1;
  1636. field_update_instance($instance);
  1637. $node = $this->drupalCreateNode(array('type' => 'article'));
  1638. $wrapper = entity_metadata_wrapper('node', $node);
  1639. $wrapper->field_text[0]->set(array('value' => "<b>The second body.</b>"));
  1640. $this->assertEqual("<p>The second body.</p>\n", $wrapper->field_text[0]->value->value(), "Setting a processed text field value and reading it again.");
  1641. // Assert the summary property is correctly removed.
  1642. $this->assertFalse(isset($wrapper->field_text[0]->summary), 'Processed text has no summary.');
  1643. // Create a text field with summary but without text processing.
  1644. $field = array(
  1645. 'field_name' => 'field_text2',
  1646. 'type' => 'text_with_summary',
  1647. 'cardinality' => 1,
  1648. );
  1649. field_create_field($field);
  1650. $instance = array(
  1651. 'field_name' => 'field_text2',
  1652. 'entity_type' => 'node',
  1653. 'label' => 'test',
  1654. 'bundle' => 'article',
  1655. 'settings' => array('text_processing' => 0),
  1656. 'widget' => array(
  1657. 'type' => 'text_textarea_with_summary',
  1658. 'weight' => -1,
  1659. ),
  1660. );
  1661. field_create_instance($instance);
  1662. $node = $this->drupalCreateNode(array('type' => 'article'));
  1663. $wrapper = entity_metadata_wrapper('node', $node);
  1664. $wrapper->field_text2->summary = 'the summary';
  1665. $wrapper->field_text2->value = 'the text';
  1666. // Try saving the node and make sure the information is still there after
  1667. // loading the node again, thus the correct data structure has been written.
  1668. node_save($node);
  1669. $node = node_load($node->nid, NULL, TRUE);
  1670. $wrapper = entity_metadata_wrapper('node', $node);
  1671. $this->assertEqual('the text', $wrapper->field_text2->value->value(), 'Text has been specified.');
  1672. $this->assertEqual('the summary', $wrapper->field_text2->summary->value(), 'Summary has been specified.');
  1673. }
  1674. /**
  1675. * Test making use of a file field.
  1676. */
  1677. function testFileFields() {
  1678. $file = $this->createFile();
  1679. // Create a file field.
  1680. $field = array(
  1681. 'field_name' => 'field_file',
  1682. 'type' => 'file',
  1683. 'cardinality' => 2,
  1684. 'settings' => array('display_field' => TRUE),
  1685. );
  1686. field_create_field($field);
  1687. $instance = array(
  1688. 'field_name' => 'field_file',
  1689. 'entity_type' => 'node',
  1690. 'label' => 'File',
  1691. 'bundle' => 'article',
  1692. 'settings' => array('description_field' => TRUE),
  1693. 'required' => FALSE,
  1694. 'widget' => array(
  1695. 'type' => 'file_generic',
  1696. 'weight' => -1,
  1697. ),
  1698. );
  1699. field_create_instance($instance);
  1700. $node = $this->drupalCreateNode(array('type' => 'article'));
  1701. $wrapper = entity_metadata_wrapper('node', $node);
  1702. $wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
  1703. $this->assertEqual($file->filename, $wrapper->field_file[0]->file->name->value(), 'File has been specified.');
  1704. $wrapper->field_file[0]->description = 'foo';
  1705. $wrapper->field_file[0]->display = TRUE;
  1706. $this->assertEqual($wrapper->field_file[0]->description->value(), 'foo', 'File description has been correctly set.');
  1707. // Try saving the node and make sure the information is still there after
  1708. // loading the node again, thus the correct data structure has been written.
  1709. node_save($node);
  1710. $node = node_load($node->nid, NULL, TRUE);
  1711. $wrapper = entity_metadata_wrapper('node', $node);
  1712. $this->assertEqual($wrapper->field_file[0]->description->value(), 'foo', 'File description has been correctly set.');
  1713. $this->assertEqual($wrapper->field_file[0]->display->value(), TRUE, 'File display value has been correctly set.');
  1714. // Test adding a new file, the display-property has to be created
  1715. // automatically.
  1716. $wrapper->field_file[1]->file = $file;
  1717. node_save($node);
  1718. $node = node_load($node->nid, NULL, TRUE);
  1719. $this->assertEqual($file->fid, $wrapper->field_file[1]->file->getIdentifier(), 'New file has been added.');
  1720. // Test adding an invalid file-field item, i.e. without any file.
  1721. try {
  1722. $wrapper->field_file[] = array('description' => 'test');
  1723. $this->fail('Exception not thrown.');
  1724. }
  1725. catch (EntityMetadataWrapperException $e) {
  1726. $this->pass('Not valid file-field item has thrown an exception.');
  1727. }
  1728. // Test remove all file-field items.
  1729. $wrapper->field_file = NULL;
  1730. $this->assertFalse($wrapper->field_file->value(), 'Removed multiple file-field items.');
  1731. }
  1732. /**
  1733. * Test making use of an image field.
  1734. */
  1735. function testImageFields() {
  1736. $file = $this->createFile('image');
  1737. // Just use the image field on the article node.
  1738. $node = $this->drupalCreateNode(array('type' => 'article'));
  1739. $wrapper = entity_metadata_wrapper('node', $node);
  1740. $wrapper->field_image = array('fid' => $file->fid);
  1741. $this->assertEqual($file->filename, $wrapper->field_image->file->name->value(), 'File has been specified.');
  1742. $wrapper->field_image->alt = 'foo';
  1743. $this->assertEqual($wrapper->field_image->alt->value(), 'foo', 'Image alt attribute has been correctly set.');
  1744. // Try saving the node and make sure the information is still there after
  1745. // loading the node again, thus the correct data structure has been written.
  1746. node_save($node);
  1747. $node = node_load($node->nid, NULL, TRUE);
  1748. $wrapper = entity_metadata_wrapper('node', $node);
  1749. $this->assertEqual($wrapper->field_image->alt->value(), 'foo', 'File description has been correctly set.');
  1750. // Test adding a new image.
  1751. $wrapper->field_image->file = $file;
  1752. node_save($node);
  1753. $node = node_load($node->nid, NULL, TRUE);
  1754. $this->assertEqual($file->fid, $wrapper->field_image->file->getIdentifier(), 'New file has been added.');
  1755. // Test adding an invalid image-field item, i.e. without any file.
  1756. try {
  1757. $wrapper->field_image = array();
  1758. $this->fail('Exception not thrown.');
  1759. }
  1760. catch (EntityMetadataWrapperException $e) {
  1761. $this->pass('Not valid image-field item has thrown an exception.');
  1762. }
  1763. }
  1764. /**
  1765. * Creates a value for the given property.
  1766. */
  1767. protected function createValue($wrapper) {
  1768. if (!isset($this->node)) {
  1769. $this->node = $this->drupalCreateNode(array('type' => 'page'));
  1770. $this->user = $this->drupalCreateUser();
  1771. $this->taxonomy_vocabulary = $this->createVocabulary();
  1772. }
  1773. if ($options = $wrapper->optionsList()) {
  1774. $options = entity_property_options_flatten($options);
  1775. return $wrapper instanceof EntityListWrapper ? array(key($options)) : key($options);
  1776. }
  1777. // For mail addresses properly pass an mail address.
  1778. $info = $wrapper->info();
  1779. if ($info['name'] == 'mail') {
  1780. return 'webmaster@example.com';
  1781. }
  1782. switch ($wrapper->type()) {
  1783. case 'decimal':
  1784. case 'integer':
  1785. case 'duration':
  1786. return 1;
  1787. case 'date':
  1788. return REQUEST_TIME;
  1789. case 'boolean':
  1790. return TRUE;
  1791. case 'token':
  1792. return drupal_strtolower($this->randomName(8));
  1793. case 'text':
  1794. return $this->randomName(32);
  1795. case 'text_formatted':
  1796. return array('value' => $this->randomName(16));
  1797. case 'list<taxonomy_term>':
  1798. return array();
  1799. default:
  1800. return $this->{$wrapper->type()};
  1801. }
  1802. }
  1803. }