entity.test 89 KB

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