entity.test 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621
  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. * Test the i18n integration.
  442. */
  443. class EntityAPIi18nItegrationTestCase extends EntityWebTestCase {
  444. public static function getInfo() {
  445. return array(
  446. 'name' => 'Entity CRUD i18n integration',
  447. 'description' => 'Tests the i18n integration provided by the Entity CRUD API.',
  448. 'group' => 'Entity API',
  449. 'dependencies' => array('i18n_string'),
  450. );
  451. }
  452. function setUp() {
  453. parent::setUp('entity_test_i18n');
  454. $this->admin_user = $this->drupalCreateUser(array('bypass node access', 'administer nodes', 'administer languages', 'administer content types', 'administer blocks', 'access administration pages'));
  455. $this->drupalLogin($this->admin_user);
  456. $this->addLanguage('de');
  457. }
  458. /**
  459. * Copied from i18n module (class Drupali18nTestCase).
  460. *
  461. * We cannot extend from Drupali18nTestCase as else the test-bot would die.
  462. */
  463. public function addLanguage($language_code) {
  464. // Check to make sure that language has not already been installed.
  465. $this->drupalGet('admin/config/regional/language');
  466. if (strpos($this->drupalGetContent(), 'enabled[' . $language_code . ']') === FALSE) {
  467. // Doesn't have language installed so add it.
  468. $edit = array();
  469. $edit['langcode'] = $language_code;
  470. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  471. // Make sure we are not using a stale list.
  472. drupal_static_reset('language_list');
  473. $languages = language_list('language');
  474. $this->assertTrue(array_key_exists($language_code, $languages), t('Language was installed successfully.'));
  475. if (array_key_exists($language_code, $languages)) {
  476. $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.'));
  477. }
  478. }
  479. elseif ($this->xpath('//input[@type="checkbox" and @name=:name and @checked="checked"]', array(':name' => 'enabled[' . $language_code . ']'))) {
  480. // It's installed and enabled. No need to do anything.
  481. $this->assertTrue(true, 'Language [' . $language_code . '] already installed and enabled.');
  482. }
  483. else {
  484. // It's installed but not enabled. Enable it.
  485. $this->assertTrue(true, 'Language [' . $language_code . '] already installed.');
  486. $this->drupalPost(NULL, array('enabled[' . $language_code . ']' => TRUE), t('Save configuration'));
  487. $this->assertRaw(t('Configuration saved.'), t('Language successfully enabled.'));
  488. }
  489. }
  490. /**
  491. * Tests the provided default controller.
  492. */
  493. function testDefaultController() {
  494. // Create test entities for the user1 and unrelated to a user.
  495. $entity = entity_create('entity_test_type', array(
  496. 'name' => 'test',
  497. 'uid' => $GLOBALS['user']->uid,
  498. 'label' => 'label-en',
  499. ));
  500. $entity->save();
  501. // Add a translation.
  502. i18n_string_textgroup('entity_test')->update_translation("entity_test_type:{$entity->name}:label", 'de', 'label-de');
  503. $default = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en');
  504. $translation = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en', 'de');
  505. $this->assertEqual($translation, 'label-de', 'Label has been translated.');
  506. $this->assertEqual($default, 'label-en', 'Default label retrieved.');
  507. // Test the helper method.
  508. $translation = $entity->getTranslation('label', 'de');
  509. $default = $entity->getTranslation('label');
  510. $this->assertEqual($translation, 'label-de', 'Label has been translated via the helper method.');
  511. $this->assertEqual($default, 'label-en', 'Default label retrieved via the helper method.');
  512. // Test updating and make sure the translation stays.
  513. $entity->name = 'test2';
  514. $entity->save();
  515. $translation = $entity->getTranslation('label', 'de');
  516. $this->assertEqual($translation, 'label-de', 'Translation survives a name change.');
  517. // Test using the wrapper to retrieve a translation.
  518. $wrapper = entity_metadata_wrapper('entity_test_type', $entity);
  519. $translation = $wrapper->language('de')->label->value();
  520. $this->assertEqual($translation, 'label-de', 'Translation retrieved via the wrapper.');
  521. // Test deleting.
  522. $entity->delete();
  523. $translation = entity_i18n_string("entity_test:entity_test_type:{$entity->name}:label", 'label-en', 'de');
  524. $this->assertEqual($translation, 'label-en', 'Translation has been deleted.');
  525. }
  526. }
  527. /**
  528. * Tests metadata wrappers.
  529. */
  530. class EntityMetadataTestCase extends EntityWebTestCase {
  531. public static function getInfo() {
  532. return array(
  533. 'name' => 'Metadata Wrapper',
  534. 'description' => 'Makes sure metadata wrapper are working right.',
  535. 'group' => 'Entity API',
  536. );
  537. }
  538. function setUp() {
  539. parent::setUp('entity', 'entity_test', 'locale');
  540. // Create a field having 4 values for testing multiple value support.
  541. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  542. $this->field = array('field_name' => $this->field_name, 'type' => 'text', 'cardinality' => 4);
  543. $this->field = field_create_field($this->field);
  544. $this->field_id = $this->field['id'];
  545. $this->instance = array(
  546. 'field_name' => $this->field_name,
  547. 'entity_type' => 'node',
  548. 'bundle' => 'page',
  549. 'label' => $this->randomName() . '_label',
  550. 'description' => $this->randomName() . '_description',
  551. 'weight' => mt_rand(0, 127),
  552. 'settings' => array(
  553. 'text_processing' => FALSE,
  554. ),
  555. 'widget' => array(
  556. 'type' => 'text_textfield',
  557. 'label' => 'Test Field',
  558. 'settings' => array(
  559. 'size' => 64,
  560. )
  561. )
  562. );
  563. field_create_instance($this->instance);
  564. // Make the body field and the node type 'page' translatable.
  565. $field = field_info_field('body');
  566. $field['translatable'] = TRUE;
  567. field_update_field($field);
  568. variable_set('language_content_type_page', 1);
  569. }
  570. /**
  571. * Creates a user and a node, then tests getting the properties.
  572. */
  573. function testEntityMetadataWrapper() {
  574. $account = $this->drupalCreateUser();
  575. // For testing sanitizing give the user a malicious user name
  576. $account = user_save($account, array('name' => '<b>BadName</b>'));
  577. $title = '<b>Is it bold?<b>';
  578. $body[LANGUAGE_NONE][0] = array('value' => '<b>The body & nothing.</b>', 'summary' => '<b>The body.</b>');
  579. $node = $this->drupalCreateNode(array('uid' => $account->uid, 'name' => $account->name, 'body' => $body, 'title' => $title, 'summary' => '', 'type' => 'page'));
  580. // First test without sanitizing.
  581. $wrapper = entity_metadata_wrapper('node', $node);
  582. $this->assertEqual('<b>Is it bold?<b>', $wrapper->title->value(), 'Getting a field value.');
  583. $this->assertEqual($node->title, $wrapper->title->raw(), 'Getting a raw property value.');
  584. // Test chaining.
  585. $this->assertEqual($account->mail, $wrapper->author->mail->value(), 'Testing chained usage.');
  586. $this->assertEqual($account->name, $wrapper->author->name->value(), 'Testing chained usage with callback and sanitizing.');
  587. // Test sanitized output.
  588. $options = array('sanitize' => TRUE);
  589. $this->assertEqual(check_plain('<b>Is it bold?<b>'), $wrapper->title->value($options), 'Getting sanitized field.');
  590. $this->assertEqual(filter_xss($node->name), $wrapper->author->name->value($options), 'Getting sanitized property with getter callback.');
  591. // Test getting an not existing property.
  592. try {
  593. echo $wrapper->dummy;
  594. $this->fail('Getting an not existing property.');
  595. }
  596. catch (EntityMetadataWrapperException $e) {
  597. $this->pass('Getting an not existing property.');
  598. }
  599. // Test setting.
  600. $wrapper->author = 0;
  601. $this->assertEqual(0, $wrapper->author->uid->value(), 'Setting a property.');
  602. try {
  603. $wrapper->url = 'dummy';
  604. $this->fail('Setting an unsupported property.');
  605. }
  606. catch (EntityMetadataWrapperException $e) {
  607. $this->pass('Setting an unsupported property.');
  608. }
  609. // Test value validation.
  610. $this->assertFalse($wrapper->author->name->validate(array(3)), 'Validation correctly checks for valid data types.');
  611. try {
  612. $wrapper->author->mail = 'foo';
  613. $this->fail('An invalid mail address has been set.');
  614. }
  615. catch (EntityMetadataWrapperException $e) {
  616. $this->pass('Setting an invalid mail address throws exception.');
  617. }
  618. // Test unsetting a required property.
  619. try {
  620. $wrapper->author = NULL;
  621. $this->fail('The required node author has been unset.');
  622. }
  623. catch (EntityMetadataWrapperException $e) {
  624. $this->pass('Unsetting the required node author throws an exception.');
  625. }
  626. // Test setting a referenced entity by id.
  627. $wrapper->author->set($GLOBALS['user']->uid);
  628. $this->assertEqual($wrapper->author->getIdentifier(), $GLOBALS['user']->uid, 'Get the identifier of a referenced entity.');
  629. $this->assertEqual($wrapper->author->uid->value(), $GLOBALS['user']->uid, 'Successfully set referenced entity using the identifier.');
  630. // Set by object.
  631. $wrapper->author->set($GLOBALS['user']);
  632. $this->assertEqual($wrapper->author->uid->value(), $GLOBALS['user']->uid, 'Successfully set referenced entity using the entity.');
  633. // Test getting by the field API processed values like the node body.
  634. $body_value = $wrapper->body->value;
  635. $this->assertEqual("<p>The body &amp; nothing.</p>\n", $body_value->value(), "Getting processed value.");
  636. $this->assertEqual("The body & nothing.\n", $body_value->value(array('decode' => TRUE)), "Decoded value.");
  637. $this->assertEqual("<b>The body & nothing.</b>", $body_value->raw(), "Raw body returned.");
  638. // Test getting the summary.
  639. $this->assertEqual("<p>The body.</p>\n", $wrapper->body->summary->value(), "Getting body summary.");
  640. $wrapper->body->set(array('value' => "<b>The second body.</b>"));
  641. $this->assertEqual("<p>The second body.</p>\n", $wrapper->body->value->value(), "Setting a processed field value and reading it again.");
  642. $this->assertEqual($node->body[LANGUAGE_NONE][0]['value'], "<b>The second body.</b>", 'Update appears in the wrapped entity.');
  643. $this->assert(isset($node->body[LANGUAGE_NONE][0]['safe_value']), 'Formatted text has been processed.');
  644. // Test translating the body on an English node.
  645. locale_add_language('de');
  646. $body['en'][0] = array('value' => '<b>English body.</b>', 'summary' => '<b>The body.</b>');
  647. $node = $this->drupalCreateNode(array('body' => $body, 'language' => 'en', 'type' => 'page'));
  648. $wrapper = entity_metadata_wrapper('node', $node);
  649. $wrapper->language('de');
  650. $languages = language_list();
  651. $this->assertEqual($wrapper->getPropertyLanguage(), $languages['de'], 'Wrapper language has been set to German');
  652. $this->assertEqual($wrapper->body->value->value(), "<p>English body.</p>\n", 'Language fallback on default language.');
  653. // Set a German text using the wrapper.
  654. $wrapper->body->set(array('value' => "<b>Der zweite Text.</b>"));
  655. $this->assertEqual($wrapper->body->value->value(), "<p>Der zweite Text.</p>\n", 'German body set and retrieved.');
  656. $wrapper->language(LANGUAGE_NONE);
  657. $this->assertEqual($wrapper->body->value->value(), "<p>English body.</p>\n", 'Default language text is still there.');
  658. // Test iterator.
  659. $type_info = entity_get_property_info('node');
  660. $this->assertFalse(array_diff_key($type_info['properties'], iterator_to_array($wrapper->getIterator())), 'Iterator is working.');
  661. foreach ($wrapper as $property) {
  662. $this->assertTrue($property instanceof EntityMetadataWrapper, 'Iterate over wrapper properties.');
  663. }
  664. // Test setting a new node.
  665. $node->title = 'foo';
  666. $wrapper->set($node);
  667. $this->assertEqual($wrapper->title->value(), 'foo', 'Changed the wrapped node.');
  668. // Test getting options lists.
  669. $this->assertEqual($wrapper->type->optionsList(), node_type_get_names(), 'Options list returned.');
  670. // Test making use of a generic 'entity' reference property the
  671. // 'entity_test' module provides. The property defaults to the node author.
  672. $this->assertEqual($wrapper->reference->uid->value(), $wrapper->author->getIdentifier(), 'Used generic entity reference property.');
  673. // Test updating a property of the generic entity reference.
  674. $wrapper->reference->name->set('foo');
  675. $this->assertEqual($wrapper->reference->name->value(), 'foo', 'Updated property of generic entity reference');
  676. // For testing, just point the reference to the node itself now.
  677. $wrapper->reference->set($wrapper);
  678. $this->assertEqual($wrapper->reference->nid->value(), $wrapper->getIdentifier(), 'Correctly updated the generic entity referenced property.');
  679. // Test saving and deleting.
  680. $wrapper->save();
  681. $wrapper->delete();
  682. $return = node_load($wrapper->getIdentifier());
  683. $this->assertFalse($return, "Node has been successfully deleted.");
  684. // Ensure changing the bundle changes available wrapper properties.
  685. $wrapper->type->set('article');
  686. $this->assertTrue(isset($wrapper->field_tags), 'Changing bundle changes available wrapper properties.');
  687. // Test labels.
  688. $user = $this->drupalCreateUser();
  689. user_save($user, array('roles' => array()));
  690. $wrapper->author = $user->uid;
  691. $this->assertEqual($wrapper->label(), $node->title, 'Entity label returned.');
  692. $this->assertEqual($wrapper->author->roles[0]->label(), t('authenticated user'), 'Label from options list returned');
  693. $this->assertEqual($wrapper->author->roles->label(), t('authenticated user'), 'Label for a list from options list returned');
  694. }
  695. /**
  696. * Test supporting multi-valued fields.
  697. */
  698. function testListMetadataWrappers() {
  699. $property = $this->field_name;
  700. $values = array();
  701. $values[LANGUAGE_NONE][0] = array('value' => '<b>2009-09-05</b>');
  702. $values[LANGUAGE_NONE][1] = array('value' => '2009-09-05');
  703. $values[LANGUAGE_NONE][2] = array('value' => '2009-08-05');
  704. $node = $this->drupalCreateNode(array('type' => 'page', $property => $values));
  705. $wrapper = entity_metadata_wrapper('node', $node);
  706. $this->assertEqual('<b>2009-09-05</b>', $wrapper->{$property}[0]->value(), 'Getting array entry.');
  707. $this->assertEqual('2009-09-05', $wrapper->{$property}->get(1)->value(), 'Getting array entry.');
  708. $this->assertEqual(3, count($wrapper->{$property}->value()), 'Getting the whole array.');
  709. // Test sanitizing
  710. $this->assertEqual(check_plain('<b>2009-09-05</b>'), $wrapper->{$property}[0]->value(array('sanitize' => TRUE)), 'Getting array entry.');
  711. // Test iterator
  712. $this->assertEqual(array_keys(iterator_to_array($wrapper->$property->getIterator())), array_keys($wrapper->$property->value()), 'Iterator is working.');
  713. foreach ($wrapper->$property as $p) {
  714. $this->assertTrue($p instanceof EntityMetadataWrapper, 'Iterate over list wrapper properties.');
  715. }
  716. // Make sure changing the array changes the actual entity property.
  717. $wrapper->{$property}[0] = '2009-10-05';
  718. unset($wrapper->{$property}[1], $wrapper->{$property}[2]);
  719. $this->assertEqual($wrapper->{$property}->value(), array('2009-10-05'), 'Setting multiple property values.');
  720. // Test setting an arbitrary list item.
  721. $list = array(0 => REQUEST_TIME);
  722. $wrapper = entity_metadata_wrapper('list<date>', $list);
  723. $wrapper[1] = strtotime('2009-09-05');
  724. $this->assertEqual($wrapper->value(), array(REQUEST_TIME, strtotime('2009-09-05')), 'Setting a list item.');
  725. $this->assertEqual($wrapper->count(), 2, 'List count is correct.');
  726. // Test using a list wrapper without data.
  727. $wrapper = entity_metadata_wrapper('list<date>');
  728. $info = array();
  729. foreach ($wrapper as $item) {
  730. $info[] = $item->info();
  731. }
  732. $this->assertTrue($info[0]['type'] == 'date', 'Iterated over empty list wrapper.');
  733. // Test using a list of entities with a list of term objects.
  734. $list = array();
  735. $list[] = entity_property_values_create_entity('taxonomy_term', array(
  736. 'name' => 'term 1',
  737. 'vocabulary' => 1,
  738. ))->save()->value();
  739. $list[] = entity_property_values_create_entity('taxonomy_term', array(
  740. 'name' => 'term 2',
  741. 'vocabulary' => 1,
  742. ))->save()->value();
  743. $wrapper = entity_metadata_wrapper('list<taxonomy_term>', $list);
  744. $this->assertTrue($wrapper[0]->name->value() == 'term 1', 'Used a list of entities.');
  745. // Test getting a list of identifiers.
  746. $ids = $wrapper->value(array('identifier' => TRUE));
  747. $this->assertTrue(!is_object($ids[0]), 'Get a list of entity ids.');
  748. $wrapper = entity_metadata_wrapper('list<taxonomy_term>', $ids);
  749. $this->assertTrue($wrapper[0]->name->value() == 'term 1', 'Created a list of entities with ids.');
  750. // Test with a list of generic entities. The list is expected to be a list
  751. // of entity wrappers, otherwise the entity type is unknown.
  752. $node = $this->drupalCreateNode(array('title' => 'node 1'));
  753. $list = array();
  754. $list[] = entity_metadata_wrapper('node', $node);
  755. $wrapper = entity_metadata_wrapper('list<entity>', $list);
  756. $this->assertEqual($wrapper[0]->title->value(), 'node 1', 'Wrapped node was found in generic list of entities.');
  757. }
  758. /**
  759. * Tests using the wrapper without any data.
  760. */
  761. function testWithoutData() {
  762. $wrapper = entity_metadata_wrapper('node', NULL, array('bundle' => 'page'));
  763. $this->assertTrue(isset($wrapper->title), 'Bundle properties have been added.');
  764. $info = $wrapper->author->mail->info();
  765. $this->assertTrue(!empty($info) && is_array($info) && isset($info['label']), 'Property info returned.');
  766. }
  767. /**
  768. * Test using access() method.
  769. */
  770. function testAccess() {
  771. // Test without data.
  772. $account = $this->drupalCreateUser(array('bypass node access'));
  773. $this->assertTrue(entity_access('view', 'node', NULL, $account), 'Access without data checked.');
  774. // Test with actual data.
  775. $values[LANGUAGE_NONE][0] = array('value' => '<b>2009-09-05</b>');
  776. $values[LANGUAGE_NONE][1] = array('value' => '2009-09-05');
  777. $node = $this->drupalCreateNode(array('type' => 'page', $this->field_name => $values));
  778. $this->assertTrue(entity_access('delete', 'node', $node, $account), 'Access with data checked.');
  779. // Test per property access without data.
  780. $account2 = $this->drupalCreateUser(array('bypass node access', 'administer nodes'));
  781. $wrapper = entity_metadata_wrapper('node', NULL, array('bundle' => 'page'));
  782. $this->assertTrue($wrapper->access('edit', $account), 'Access to node granted.');
  783. $this->assertFalse($wrapper->status->access('edit', $account), 'Access for admin property denied.');
  784. $this->assertTrue($wrapper->status->access('edit', $account2), 'Access for admin property allowed for the admin.');
  785. // Test per property access with data.
  786. $wrapper = entity_metadata_wrapper('node', $node, array('bundle' => 'page'));
  787. $this->assertFalse($wrapper->status->access('edit', $account), 'Access for admin property denied.');
  788. $this->assertTrue($wrapper->status->access('edit', $account2), 'Access for admin property allowed for the admin.');
  789. // Test field level access.
  790. $this->assertTrue($wrapper->{$this->field_name}->access('view'), 'Field access granted.');
  791. }
  792. /**
  793. * Tests using a data structure with passed in metadata.
  794. */
  795. function testDataStructureWrapper() {
  796. $log_entry = array(
  797. 'type' => 'entity',
  798. 'message' => $this->randomName(8),
  799. 'variables' => array(),
  800. 'severity' => WATCHDOG_NOTICE,
  801. 'link' => '',
  802. 'user' => $GLOBALS['user'],
  803. );
  804. $info['property info'] = array(
  805. 'type' => array('type' => 'text', 'label' => 'The category to which this message belongs.'),
  806. 'message' => array('type' => 'text', 'label' => 'The log message.'),
  807. 'user' => array('type' => 'user', 'label' => 'The user causing the log entry.'),
  808. );
  809. $wrapper = entity_metadata_wrapper('log_entry', $log_entry, $info);
  810. $this->assertEqual($wrapper->user->name->value(), $GLOBALS['user']->name, 'Wrapped custom entity.');
  811. }
  812. /**
  813. * Tests using entity_property_query().
  814. */
  815. function testEntityQuery() {
  816. // Creat a test node.
  817. $title = '<b>Is it bold?<b>';
  818. $values[LANGUAGE_NONE][0] = array('value' => 'foo');
  819. $node = $this->drupalCreateNode(array($this->field_name => $values, 'title' => $title, 'uid' => $GLOBALS['user']->uid));
  820. $results = entity_property_query('node', 'title', $title);
  821. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given title.');
  822. $results = entity_property_query('node', $this->field_name, 'foo');
  823. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given field value.');
  824. $results = entity_property_query('node', $this->field_name, array('foo', 'bar'));
  825. $this->assertEqual($results, array($node->nid), 'Queried nodes with a list of possible values.');
  826. $results = entity_property_query('node', 'author', $GLOBALS['user']);
  827. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given auhtor.');
  828. // Create another test node and try querying for tags.
  829. $tag = entity_property_values_create_entity('taxonomy_term', array(
  830. 'name' => $this->randomName(),
  831. 'vocabulary' => 1,
  832. ))->save();
  833. $field_tag_value[LANGUAGE_NONE][0]['tid'] = $tag->getIdentifier();
  834. $node = $this->drupalCreateNode(array('type' => 'article', 'field_tags' => $field_tag_value));
  835. // Try query-ing with a single value.
  836. $results = entity_property_query('node', 'field_tags', $tag->getIdentifier());
  837. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given term id.');
  838. $results = entity_property_query('node', 'field_tags', $tag->value());
  839. $this->assertEqual($results, array($node->nid), 'Queried nodes with a given term object.');
  840. // Try query-ing with a list of possible values.
  841. $results = entity_property_query('node', 'field_tags', array($tag->getIdentifier()));
  842. $this->assertEqual($results, array($node->nid), 'Queried nodes with a list of term ids.');
  843. }
  844. /**
  845. * Tests serializing data wrappers, in particular for EntityDrupalWrapper.
  846. */
  847. function testWrapperSerialization() {
  848. $node = $this->drupalCreateNode();
  849. $wrapper = entity_metadata_wrapper('node', $node);
  850. $this->assertTrue($wrapper->value() == $node, 'Data correctly wrapped.');
  851. // Test serializing and make sure only the node id is stored.
  852. $this->assertTrue(strpos(serialize($wrapper), $node->title) === FALSE, 'Node has been correctly serialized.');
  853. $this->assertEqual(unserialize(serialize($wrapper))->title->value(), $node->title, 'Serializing works right.');
  854. $wrapper2 = unserialize(serialize($wrapper));
  855. // Test serializing the unloaded wrapper.
  856. $this->assertEqual(unserialize(serialize($wrapper2))->title->value(), $node->title, 'Serializing works right.');
  857. // Test loading a not more existing node.
  858. $s = serialize($wrapper2);
  859. node_delete($node->nid);
  860. $this->assertFalse(node_load($node->nid), 'Node deleted.');
  861. $value = unserialize($s)->value();
  862. $this->assertNull($value, 'Tried to load not existing node.');
  863. }
  864. }
  865. /**
  866. * Tests provided entity property info of the core modules.
  867. */
  868. class EntityTokenTestCase extends EntityWebTestCase {
  869. public static function getInfo() {
  870. return array(
  871. 'name' => 'Entity tokens',
  872. 'description' => 'Tests provided tokens for entity properties.',
  873. 'group' => 'Entity API',
  874. );
  875. }
  876. function setUp() {
  877. parent::setUp('entity_token');
  878. }
  879. /**
  880. * Tests whether token support is basically working.
  881. */
  882. function testTokenSupport() {
  883. // Test basic tokens.
  884. $node = $this->drupalCreateNode(array('sticky' => TRUE, 'promote' => FALSE));
  885. $text = "Sticky: [node:sticky] Promote: [node:promote] User: [site:current-user:name]";
  886. $true = t('true');
  887. $false = t('false');
  888. $user_name = $GLOBALS['user']->name;
  889. $target = "Sticky: $true Promote: $false User: $user_name";
  890. $replace = token_replace($text, array('node' => $node));
  891. $this->assertEqual($replace, $target, 'Provided tokens basically work.');
  892. // Test multiple-value tokens using the tags field of articles.
  893. for ($i = 0; $i < 4; $i++) {
  894. $tags[$i] = entity_property_values_create_entity('taxonomy_term', array(
  895. 'name' => $this->randomName(),
  896. 'vocabulary' => 1,
  897. ))->save();
  898. $field_value[LANGUAGE_NONE][$i]['tid'] = $tags[$i]->getIdentifier();
  899. $labels[$i] = $tags[$i]->label();
  900. }
  901. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', 'field_tags' => $field_value));
  902. $text = "Tags: [node:field-tags] First: [node:field-tags:0] 2nd name: [node:field-tags:1:name] 1st vocab [node:field-tags:0:vocabulary]";
  903. $tag_labels = implode(', ', $labels);
  904. $target = "Tags: $tag_labels First: $labels[0] 2nd name: $labels[1] 1st vocab {$tags[0]->vocabulary->label()}";
  905. $replace = token_replace($text, array('node' => $node));
  906. $this->assertEqual($replace, $target, 'Multiple-value token replacements have been replaced.');
  907. // Make sure not existing values are not handled.
  908. $replace = token_replace("[node:field-tags:43]", array('node' => $node));
  909. $this->assertEqual($replace, "[node:field-tags:43]", 'Not existing values are not replaced.');
  910. // Test data-structure tokens like [site:current-page:url].
  911. $replace = token_replace("[site:current-page:url]", array());
  912. $this->assertEqual($replace, $GLOBALS['base_root'] . request_uri(), 'Token replacements of data structure properties replaced.');
  913. // Test chaining of data-structure tokens using an image-field.
  914. $file = $this->createFile('image');
  915. $node = $this->drupalCreateNode(array('type' => 'article'));
  916. $wrapper = entity_metadata_wrapper('node', $node);
  917. $wrapper->field_image = array('fid' => $file->fid);
  918. $replace = token_replace("[node:field-image:file:name]", array('node' => $node));
  919. $this->assertEqual($replace, $wrapper->field_image->file->name->value(), 'Token replacements of an image field have been replaced.');
  920. }
  921. }
  922. /**
  923. * Tests provided entity property info of the core modules.
  924. */
  925. class EntityMetadataIntegrationTestCase extends EntityWebTestCase {
  926. public static function getInfo() {
  927. return array(
  928. 'name' => 'Property info core integration',
  929. 'description' => 'Tests using metadata wrapper for drupal core.',
  930. 'group' => 'Entity API',
  931. );
  932. }
  933. function setUp() {
  934. parent::setUp('entity', 'book', 'statistics', 'locale');
  935. }
  936. protected function assertException($wrapper, $name, $text = NULL) {
  937. $this->assertTrue(isset($wrapper->$name), 'Property wrapper ' . check_plain($name) . ' exists.');
  938. $text = isset($text) ? $text : 'Getting the not existing property ' . $name . ' throws exception.';
  939. try {
  940. $wrapper->$name->value();
  941. $this->fail($text);
  942. }
  943. catch (EntityMetadataWrapperException $e) {
  944. $this->pass($text);
  945. }
  946. }
  947. protected function assertEmpty($wrapper, $name) {
  948. $this->assertTrue(isset($wrapper->$name), 'Property ' . check_plain($name) . ' exists.');
  949. $this->assertTrue($wrapper->$name->value() === NULL, 'Property ' . check_plain($name) . ' is empty.');
  950. }
  951. protected function assertValue($wrapper, $key) {
  952. $this->assertTrue($wrapper->$key->value() !== NULL, check_plain($key) . ' property returned.');
  953. $info = $wrapper->$key->info();
  954. if (!empty($info['raw getter callback'])) {
  955. // Also test getting the raw value
  956. $this->assertTrue($wrapper->$key->raw() !== NULL, check_plain($key) . ' raw value returned.');
  957. }
  958. }
  959. /**
  960. * Test book module integration.
  961. */
  962. function testBookModule() {
  963. $title = 'Book 1';
  964. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'book'));
  965. $node2 = $this->drupalCreateNode(array('type' => 'book', 'book' => array('bid' => $node->nid)));
  966. $node3 = $this->drupalCreateNode(array('type' => 'page'));
  967. // Test whether the properties work.
  968. $wrapper = entity_metadata_wrapper('node', $node2);
  969. $this->assertEqual("Book 1", $wrapper->book->title->value(), "Book title returned.");
  970. $this->assertEqual($node->nid, $wrapper->book->nid->value(), "Book id returned.");
  971. // Try using book properties for no book nodes.
  972. $wrapper = entity_metadata_wrapper('node', $node3);
  973. $this->assertException($wrapper, 'book');
  974. }
  975. /**
  976. * Test properties of a comment.
  977. */
  978. function testComments() {
  979. $title = 'Node 1';
  980. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'page'));
  981. $account = $this->drupalCreateUser();
  982. $comment = (object)array(
  983. 'subject' => 'topic',
  984. 'nid' => $node->nid,
  985. 'uid' => $account->uid,
  986. 'cid' => FALSE,
  987. 'pid' => 0,
  988. 'homepage' => '',
  989. 'language' => LANGUAGE_NONE,
  990. 'hostname' => ip_address(),
  991. );
  992. $comment->comment_body[LANGUAGE_NONE][0] = array('value' => 'text', 'format' => 0);
  993. comment_save($comment);
  994. $wrapper = entity_metadata_wrapper('comment', $comment);
  995. foreach ($wrapper as $key => $value) {
  996. if ($key != 'parent') {
  997. $this->assertValue($wrapper, $key);
  998. }
  999. }
  1000. $this->assertEmpty($wrapper, 'parent');
  1001. }
  1002. /**
  1003. * Test all properties of a node.
  1004. */
  1005. function testNodeProperties() {
  1006. $title = 'Book 1';
  1007. $node = $this->drupalCreateNode(array('title' => $title, 'type' => 'page'));
  1008. $wrapper = entity_metadata_wrapper('node', $node);
  1009. foreach ($wrapper as $key => $value) {
  1010. if ($key != 'book' && $key != 'source' && $key != 'last_view') {
  1011. $this->assertValue($wrapper, $key);
  1012. }
  1013. }
  1014. $this->assertException($wrapper, 'book');
  1015. $this->assertEmpty($wrapper, 'source');
  1016. $this->assertException($wrapper->source, 'title');
  1017. $this->assertEmpty($wrapper, 'last_view');
  1018. }
  1019. /**
  1020. * Tests properties provided by the taxonomy module.
  1021. */
  1022. function testTaxonomyProperties() {
  1023. $vocab = $this->createVocabulary();
  1024. $term_parent = entity_property_values_create_entity('taxonomy_term', array(
  1025. 'name' => $this->randomName(),
  1026. 'vocabulary' => $vocab,
  1027. ))->save()->value();
  1028. $term_parent2 = entity_property_values_create_entity('taxonomy_term', array(
  1029. 'name' => $this->randomName(),
  1030. 'vocabulary' => $vocab,
  1031. ))->save()->value();
  1032. $term = entity_property_values_create_entity('taxonomy_term', array(
  1033. 'name' => $this->randomName(),
  1034. 'vocabulary' => $vocab,
  1035. 'description' => $this->randomString(),
  1036. 'weight' => mt_rand(0, 10),
  1037. 'parent' => array($term_parent->tid),
  1038. ))->save()->value();
  1039. $wrapper = entity_metadata_wrapper('taxonomy_term', $term);
  1040. foreach ($wrapper as $key => $value) {
  1041. $this->assertValue($wrapper, $key);
  1042. }
  1043. // Test setting another parent using the full object.
  1044. $wrapper->parent[] = $term_parent2;
  1045. $this->assertEqual($wrapper->parent[1]->getIdentifier(), $term_parent2->tid, 'Term parent added.');
  1046. $parents = $wrapper->parent->value();
  1047. $tids = $term_parent->tid . ':' . $term_parent2->tid;
  1048. $this->assertEqual($parents[0]->tid . ':' . $parents[1]->tid, $tids, 'Parents returned.');
  1049. $this->assertEqual(implode(':', $wrapper->parent->value(array('identifier' => TRUE))), $tids, 'Parent ids returned.');
  1050. // Test vocabulary.
  1051. foreach ($wrapper->vocabulary as $key => $value) {
  1052. $this->assertValue($wrapper->vocabulary, $key);
  1053. }
  1054. // Test field integration.
  1055. $tags[LANGUAGE_NONE][0]['tid'] = $term->tid;
  1056. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', 'field_tags' => $tags));
  1057. $wrapper = entity_metadata_wrapper('node', $node);
  1058. $this->assertEqual($wrapper->field_tags[0]->name->value(), $term->name, 'Get an associated tag of a node with the wrapper.');
  1059. $wrapper->field_tags[1] = $term_parent;
  1060. $tags = $wrapper->field_tags->value();
  1061. $this->assertEqual($tags[1]->tid, $term_parent->tid, 'Associated a new tag with a node.');
  1062. $this->assertEqual($tags[0]->tid, $term->tid, 'Previsous set association kept.');
  1063. // Test getting a list of identifiers.
  1064. $tags = $wrapper->field_tags->value(array('identifier' => TRUE));
  1065. $this->assertEqual($tags, array($term->tid, $term_parent->tid), 'List of referenced term identifiers returned.');
  1066. // Test setting tags by using ids.
  1067. $wrapper->field_tags->set(array(2));
  1068. $this->assertEqual($wrapper->field_tags[0]->tid->value(), 2, 'Specified tags by a list of term ids.');
  1069. // Test unsetting all tags.
  1070. $wrapper->field_tags = NULL;
  1071. $this->assertFalse($wrapper->field_tags->value(), 'Unset all tags from a node.');
  1072. // Test setting entity references to NULL.
  1073. // Create a taxonomy term field for that purpose.
  1074. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  1075. $field = array('field_name' => $field_name, 'type' => 'taxonomy_term_reference', 'cardinality' => 1);
  1076. $field = field_create_field($field);
  1077. $field_id = $field['id'];
  1078. $field_instance = array(
  1079. 'field_name' => $field_name,
  1080. 'entity_type' => 'node',
  1081. 'bundle' => 'article',
  1082. 'label' => $this->randomName() . '_label',
  1083. 'description' => $this->randomName() . '_description',
  1084. 'weight' => mt_rand(0, 127),
  1085. 'widget' => array(
  1086. 'type' => 'options_select',
  1087. 'label' => 'Test term field',
  1088. )
  1089. );
  1090. field_create_instance($field_instance);
  1091. $term_field[LANGUAGE_NONE][0]['tid'] = $term->tid;
  1092. $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', $field_name => $term_field));
  1093. $wrapper = entity_metadata_wrapper('node', $node);
  1094. $wrapper->$field_name->set(NULL);
  1095. $termref = $wrapper->$field_name->value();
  1096. $this->assertNull($termref, 'Unset of a term reference successful.');
  1097. }
  1098. /**
  1099. * Test all properties of a user.
  1100. */
  1101. function testUserProperties() {
  1102. $account = $this->drupalCreateUser();
  1103. $account->login = REQUEST_TIME;
  1104. $account->access = REQUEST_TIME;
  1105. $wrapper = entity_metadata_wrapper('user', $account);
  1106. foreach ($wrapper as $key => $value) {
  1107. $this->assertValue($wrapper, $key);
  1108. }
  1109. }
  1110. /**
  1111. * Test properties provided by system module.
  1112. */
  1113. function testSystemProperties() {
  1114. $wrapper = entity_metadata_site_wrapper();
  1115. foreach ($wrapper as $key => $value) {
  1116. $this->assertValue($wrapper, $key);
  1117. }
  1118. // Test page request related properties.
  1119. foreach ($wrapper->current_page as $key => $value) {
  1120. $this->assertValue($wrapper->current_page, $key);
  1121. }
  1122. // Test files.
  1123. $file = $this->createFile();
  1124. $wrapper = entity_metadata_wrapper('file', $file);
  1125. foreach ($wrapper as $key => $value) {
  1126. $this->assertValue($wrapper, $key);
  1127. }
  1128. }
  1129. /**
  1130. * Runs some generic tests on each entity.
  1131. */
  1132. function testCRUDfunctions() {
  1133. $info = entity_get_info();
  1134. foreach ($info as $entity_type => $entity_info) {
  1135. // Test using access callback.
  1136. entity_access('view', $entity_type);
  1137. entity_access('update', $entity_type);
  1138. entity_access('create', $entity_type);
  1139. entity_access('delete', $entity_type);
  1140. // Test creating the entity.
  1141. if (!isset($entity_info['creation callback'])) {
  1142. continue;
  1143. }
  1144. // Populate $values with all values that are setable. They will be set
  1145. // with an metadata wrapper, so we also test setting that way.
  1146. $values = array();
  1147. foreach (entity_metadata_wrapper($entity_type) as $name => $wrapper) {
  1148. $info = $wrapper->info();
  1149. if (!empty($info['setter callback'])) {
  1150. $values[$name] = $this->createValue($wrapper);
  1151. }
  1152. }
  1153. $entity = entity_property_values_create_entity($entity_type, $values)->value();
  1154. $this->assertTrue($entity, "Created $entity_type and set all setable values.");
  1155. // Save the new entity.
  1156. $return = entity_save($entity_type, $entity);
  1157. if ($return === FALSE) {
  1158. continue; // No support for saving.
  1159. }
  1160. $id = entity_metadata_wrapper($entity_type, $entity)->getIdentifier();
  1161. $this->assertTrue($id, "$entity_type has been successfully saved.");
  1162. // And delete it.
  1163. $return = entity_delete($entity_type, $id);
  1164. if ($return === FALSE) {
  1165. continue; // No support for deleting.
  1166. }
  1167. $return = entity_load_single($entity_type, $id);
  1168. $this->assertFalse($return, "$entity_type has been successfully deleted.");
  1169. }
  1170. }
  1171. /**
  1172. * Test making use of a text fields.
  1173. */
  1174. function testTextFields() {
  1175. // Create a simple text field without text processing.
  1176. $field = array(
  1177. 'field_name' => 'field_text',
  1178. 'type' => 'text',
  1179. 'cardinality' => 2,
  1180. );
  1181. field_create_field($field);
  1182. $instance = array(
  1183. 'field_name' => 'field_text',
  1184. 'entity_type' => 'node',
  1185. 'label' => 'test',
  1186. 'bundle' => 'article',
  1187. 'widget' => array(
  1188. 'type' => 'text_textfield',
  1189. 'weight' => -1,
  1190. ),
  1191. );
  1192. field_create_instance($instance);
  1193. $node = $this->drupalCreateNode(array('type' => 'article'));
  1194. $wrapper = entity_metadata_wrapper('node', $node);
  1195. $wrapper->field_text[0] = 'the text';
  1196. // Try saving the node and make sure the information is still there after
  1197. // loading the node again, thus the correct data structure has been written.
  1198. node_save($node);
  1199. $node = node_load($node->nid, NULL, TRUE);
  1200. $wrapper = entity_metadata_wrapper('node', $node);
  1201. $this->assertEqual('the text', $wrapper->field_text[0]->value(), 'Text has been specified.');
  1202. // Now activate text processing.
  1203. $instance['settings']['text_processing'] = 1;
  1204. field_update_instance($instance);
  1205. $node = $this->drupalCreateNode(array('type' => 'article'));
  1206. $wrapper = entity_metadata_wrapper('node', $node);
  1207. $wrapper->field_text[0]->set(array('value' => "<b>The second body.</b>"));
  1208. $this->assertEqual("<p>The second body.</p>\n", $wrapper->field_text[0]->value->value(), "Setting a processed text field value and reading it again.");
  1209. // Assert the summary property is correctly removed.
  1210. $this->assertFalse(isset($wrapper->field_text[0]->summary), 'Processed text has no summary.');
  1211. // Create a text field with summary but without text processing.
  1212. $field = array(
  1213. 'field_name' => 'field_text2',
  1214. 'type' => 'text_with_summary',
  1215. 'cardinality' => 1,
  1216. );
  1217. field_create_field($field);
  1218. $instance = array(
  1219. 'field_name' => 'field_text2',
  1220. 'entity_type' => 'node',
  1221. 'label' => 'test',
  1222. 'bundle' => 'article',
  1223. 'settings' => array('text_processing' => 0),
  1224. 'widget' => array(
  1225. 'type' => 'text_textarea_with_summary',
  1226. 'weight' => -1,
  1227. ),
  1228. );
  1229. field_create_instance($instance);
  1230. $node = $this->drupalCreateNode(array('type' => 'article'));
  1231. $wrapper = entity_metadata_wrapper('node', $node);
  1232. $wrapper->field_text2->summary = 'the summary';
  1233. $wrapper->field_text2->value = 'the text';
  1234. // Try saving the node and make sure the information is still there after
  1235. // loading the node again, thus the correct data structure has been written.
  1236. node_save($node);
  1237. $node = node_load($node->nid, NULL, TRUE);
  1238. $wrapper = entity_metadata_wrapper('node', $node);
  1239. $this->assertEqual('the text', $wrapper->field_text2->value->value(), 'Text has been specified.');
  1240. $this->assertEqual('the summary', $wrapper->field_text2->summary->value(), 'Summary has been specified.');
  1241. }
  1242. /**
  1243. * Test making use of a file field.
  1244. */
  1245. function testFileFields() {
  1246. $file = $this->createFile();
  1247. // Create a file field.
  1248. $field = array(
  1249. 'field_name' => 'field_file',
  1250. 'type' => 'file',
  1251. 'cardinality' => 2,
  1252. 'settings' => array('display_field' => TRUE),
  1253. );
  1254. field_create_field($field);
  1255. $instance = array(
  1256. 'field_name' => 'field_file',
  1257. 'entity_type' => 'node',
  1258. 'label' => 'File',
  1259. 'bundle' => 'article',
  1260. 'settings' => array('description_field' => TRUE),
  1261. 'required' => FALSE,
  1262. 'widget' => array(
  1263. 'type' => 'file_generic',
  1264. 'weight' => -1,
  1265. ),
  1266. );
  1267. field_create_instance($instance);
  1268. $node = $this->drupalCreateNode(array('type' => 'article'));
  1269. $wrapper = entity_metadata_wrapper('node', $node);
  1270. $wrapper->field_file[0] = array('fid' => $file->fid, 'display' => FALSE);
  1271. $this->assertEqual($file->filename, $wrapper->field_file[0]->file->name->value(), 'File has been specified.');
  1272. $wrapper->field_file[0]->description = 'foo';
  1273. $wrapper->field_file[0]->display = TRUE;
  1274. $this->assertEqual($wrapper->field_file[0]->description->value(), 'foo', 'File description has been correctly set.');
  1275. // Try saving the node and make sure the information is still there after
  1276. // loading the node again, thus the correct data structure has been written.
  1277. node_save($node);
  1278. $node = node_load($node->nid, NULL, TRUE);
  1279. $wrapper = entity_metadata_wrapper('node', $node);
  1280. $this->assertEqual($wrapper->field_file[0]->description->value(), 'foo', 'File description has been correctly set.');
  1281. $this->assertEqual($wrapper->field_file[0]->display->value(), TRUE, 'File display value has been correctly set.');
  1282. // Test adding a new file, the display-property has to be created
  1283. // automatically.
  1284. $wrapper->field_file[1]->file = $file;
  1285. node_save($node);
  1286. $node = node_load($node->nid, NULL, TRUE);
  1287. $this->assertEqual($file->fid, $wrapper->field_file[1]->file->getIdentifier(), 'New file has been added.');
  1288. // Test adding an invalid file-field item, i.e. without any file.
  1289. try {
  1290. $wrapper->field_file[] = array('description' => 'test');
  1291. $this->fail('Exception not thrown.');
  1292. }
  1293. catch (EntityMetadataWrapperException $e) {
  1294. $this->pass('Not valid file-field item has thrown an exception.');
  1295. }
  1296. // Test remove all file-field items.
  1297. $wrapper->field_file = NULL;
  1298. $this->assertFalse($wrapper->field_file->value(), 'Removed multiple file-field items.');
  1299. }
  1300. /**
  1301. * Test making use of an image field.
  1302. */
  1303. function testImageFields() {
  1304. $file = $this->createFile('image');
  1305. // Just use the image field on the article node.
  1306. $node = $this->drupalCreateNode(array('type' => 'article'));
  1307. $wrapper = entity_metadata_wrapper('node', $node);
  1308. $wrapper->field_image = array('fid' => $file->fid);
  1309. $this->assertEqual($file->filename, $wrapper->field_image->file->name->value(), 'File has been specified.');
  1310. $wrapper->field_image->alt = 'foo';
  1311. $this->assertEqual($wrapper->field_image->alt->value(), 'foo', 'Image alt attribute has been correctly set.');
  1312. // Try saving the node and make sure the information is still there after
  1313. // loading the node again, thus the correct data structure has been written.
  1314. node_save($node);
  1315. $node = node_load($node->nid, NULL, TRUE);
  1316. $wrapper = entity_metadata_wrapper('node', $node);
  1317. $this->assertEqual($wrapper->field_image->alt->value(), 'foo', 'File description has been correctly set.');
  1318. // Test adding a new image.
  1319. $wrapper->field_image->file = $file;
  1320. node_save($node);
  1321. $node = node_load($node->nid, NULL, TRUE);
  1322. $this->assertEqual($file->fid, $wrapper->field_image->file->getIdentifier(), 'New file has been added.');
  1323. // Test adding an invalid image-field item, i.e. without any file.
  1324. try {
  1325. $wrapper->field_image = array();
  1326. $this->fail('Exception not thrown.');
  1327. }
  1328. catch (EntityMetadataWrapperException $e) {
  1329. $this->pass('Not valid image-field item has thrown an exception.');
  1330. }
  1331. }
  1332. /**
  1333. * Creates a value for the given property.
  1334. */
  1335. protected function createValue($wrapper) {
  1336. if (!isset($this->node)) {
  1337. $this->node = $this->drupalCreateNode(array('type' => 'page'));
  1338. $this->user = $this->drupalCreateUser();
  1339. $this->taxonomy_vocabulary = $this->createVocabulary();
  1340. }
  1341. if ($options = $wrapper->optionsList()) {
  1342. $options = entity_property_options_flatten($options);
  1343. return $wrapper instanceof EntityListWrapper ? array(key($options)) : key($options);
  1344. }
  1345. // For mail addresses properly pass an mail address.
  1346. $info = $wrapper->info();
  1347. if ($info['name'] == 'mail') {
  1348. return 'webmaster@example.com';
  1349. }
  1350. switch ($wrapper->type()) {
  1351. case 'decimal':
  1352. case 'integer':
  1353. case 'duration':
  1354. return 1;
  1355. case 'date':
  1356. return REQUEST_TIME;
  1357. case 'boolean':
  1358. return TRUE;
  1359. case 'token':
  1360. return drupal_strtolower($this->randomName(8));
  1361. case 'text':
  1362. return $this->randomName(32);
  1363. case 'text_formatted':
  1364. return array('value' => $this->randomName(16));
  1365. case 'list<taxonomy_term>':
  1366. return array();
  1367. default:
  1368. return $this->{$wrapper->type()};
  1369. }
  1370. }
  1371. }