entity.test 93 KB

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