entity.test 70 KB

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