field.test 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406
  1. <?php
  2. /**
  3. * @file
  4. * Tests for field.module.
  5. */
  6. /**
  7. * Parent class for Field API tests.
  8. */
  9. class FieldTestCase extends DrupalWebTestCase {
  10. var $default_storage = 'field_sql_storage';
  11. /**
  12. * Set the default field storage backend for fields created during tests.
  13. */
  14. function setUp() {
  15. // Since this is a base class for many test cases, support the same
  16. // flexibility that DrupalWebTestCase::setUp() has for the modules to be
  17. // passed in as either an array or a variable number of string arguments.
  18. $modules = func_get_args();
  19. if (isset($modules[0]) && is_array($modules[0])) {
  20. $modules = $modules[0];
  21. }
  22. parent::setUp($modules);
  23. // Set default storage backend.
  24. variable_set('field_storage_default', $this->default_storage);
  25. }
  26. /**
  27. * Generate random values for a field_test field.
  28. *
  29. * @param $cardinality
  30. * Number of values to generate.
  31. * @return
  32. * An array of random values, in the format expected for field values.
  33. */
  34. function _generateTestFieldValues($cardinality) {
  35. $values = array();
  36. for ($i = 0; $i < $cardinality; $i++) {
  37. // field_test fields treat 0 as 'empty value'.
  38. $values[$i]['value'] = mt_rand(1, 127);
  39. }
  40. return $values;
  41. }
  42. /**
  43. * Assert that a field has the expected values in an entity.
  44. *
  45. * This function only checks a single column in the field values.
  46. *
  47. * @param $entity
  48. * The entity to test.
  49. * @param $field_name
  50. * The name of the field to test
  51. * @param $langcode
  52. * The language code for the values.
  53. * @param $expected_values
  54. * The array of expected values.
  55. * @param $column
  56. * (Optional) the name of the column to check.
  57. */
  58. function assertFieldValues($entity, $field_name, $langcode, $expected_values, $column = 'value') {
  59. $e = clone $entity;
  60. field_attach_load('test_entity', array($e->ftid => $e));
  61. $values = isset($e->{$field_name}[$langcode]) ? $e->{$field_name}[$langcode] : array();
  62. $this->assertEqual(count($values), count($expected_values), t('Expected number of values were saved.'));
  63. foreach ($expected_values as $key => $value) {
  64. $this->assertEqual($values[$key][$column], $value, t('Value @value was saved correctly.', array('@value' => $value)));
  65. }
  66. }
  67. }
  68. class FieldAttachTestCase extends FieldTestCase {
  69. function setUp() {
  70. // Since this is a base class for many test cases, support the same
  71. // flexibility that DrupalWebTestCase::setUp() has for the modules to be
  72. // passed in as either an array or a variable number of string arguments.
  73. $modules = func_get_args();
  74. if (isset($modules[0]) && is_array($modules[0])) {
  75. $modules = $modules[0];
  76. }
  77. if (!in_array('field_test', $modules)) {
  78. $modules[] = 'field_test';
  79. }
  80. parent::setUp($modules);
  81. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  82. $this->field = array('field_name' => $this->field_name, 'type' => 'test_field', 'cardinality' => 4);
  83. $this->field = field_create_field($this->field);
  84. $this->field_id = $this->field['id'];
  85. $this->instance = array(
  86. 'field_name' => $this->field_name,
  87. 'entity_type' => 'test_entity',
  88. 'bundle' => 'test_bundle',
  89. 'label' => $this->randomName() . '_label',
  90. 'description' => $this->randomName() . '_description',
  91. 'weight' => mt_rand(0, 127),
  92. 'settings' => array(
  93. 'test_instance_setting' => $this->randomName(),
  94. ),
  95. 'widget' => array(
  96. 'type' => 'test_field_widget',
  97. 'label' => 'Test Field',
  98. 'settings' => array(
  99. 'test_widget_setting' => $this->randomName(),
  100. )
  101. )
  102. );
  103. field_create_instance($this->instance);
  104. }
  105. }
  106. /**
  107. * Unit test class for storage-related field_attach_* functions.
  108. *
  109. * All field_attach_* test work with all field_storage plugins and
  110. * all hook_field_attach_pre_{load,insert,update}() hooks.
  111. */
  112. class FieldAttachStorageTestCase extends FieldAttachTestCase {
  113. public static function getInfo() {
  114. return array(
  115. 'name' => 'Field attach tests (storage-related)',
  116. 'description' => 'Test storage-related Field Attach API functions.',
  117. 'group' => 'Field API',
  118. );
  119. }
  120. /**
  121. * Check field values insert, update and load.
  122. *
  123. * Works independently of the underlying field storage backend. Inserts or
  124. * updates random field data and then loads and verifies the data.
  125. */
  126. function testFieldAttachSaveLoad() {
  127. // Configure the instance so that we test hook_field_load() (see
  128. // field_test_field_load() in field_test.module).
  129. $this->instance['settings']['test_hook_field_load'] = TRUE;
  130. field_update_instance($this->instance);
  131. $langcode = LANGUAGE_NONE;
  132. $entity_type = 'test_entity';
  133. $values = array();
  134. // TODO : test empty values filtering and "compression" (store consecutive deltas).
  135. // Preparation: create three revisions and store them in $revision array.
  136. for ($revision_id = 0; $revision_id < 3; $revision_id++) {
  137. $revision[$revision_id] = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
  138. // Note: we try to insert one extra value.
  139. $values[$revision_id] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
  140. $current_revision = $revision_id;
  141. // If this is the first revision do an insert.
  142. if (!$revision_id) {
  143. $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
  144. field_attach_insert($entity_type, $revision[$revision_id]);
  145. }
  146. else {
  147. // Otherwise do an update.
  148. $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
  149. field_attach_update($entity_type, $revision[$revision_id]);
  150. }
  151. }
  152. // Confirm current revision loads the correct data.
  153. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  154. field_attach_load($entity_type, array(0 => $entity));
  155. // Number of values per field loaded equals the field cardinality.
  156. $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], t('Current revision: expected number of values'));
  157. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  158. // The field value loaded matches the one inserted or updated.
  159. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'] , $values[$current_revision][$delta]['value'], t('Current revision: expected value %delta was found.', array('%delta' => $delta)));
  160. // The value added in hook_field_load() is found.
  161. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['additional_key'], 'additional_value', t('Current revision: extra information for value %delta was found', array('%delta' => $delta)));
  162. }
  163. // Confirm each revision loads the correct data.
  164. foreach (array_keys($revision) as $revision_id) {
  165. $entity = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
  166. field_attach_load_revision($entity_type, array(0 => $entity));
  167. // Number of values per field loaded equals the field cardinality.
  168. $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], t('Revision %revision_id: expected number of values.', array('%revision_id' => $revision_id)));
  169. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  170. // The field value loaded matches the one inserted or updated.
  171. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['value'], $values[$revision_id][$delta]['value'], t('Revision %revision_id: expected value %delta was found.', array('%revision_id' => $revision_id, '%delta' => $delta)));
  172. // The value added in hook_field_load() is found.
  173. $this->assertEqual($entity->{$this->field_name}[$langcode][$delta]['additional_key'], 'additional_value', t('Revision %revision_id: extra information for value %delta was found', array('%revision_id' => $revision_id, '%delta' => $delta)));
  174. }
  175. }
  176. }
  177. /**
  178. * Test the 'multiple' load feature.
  179. */
  180. function testFieldAttachLoadMultiple() {
  181. $entity_type = 'test_entity';
  182. $langcode = LANGUAGE_NONE;
  183. // Define 2 bundles.
  184. $bundles = array(
  185. 1 => 'test_bundle_1',
  186. 2 => 'test_bundle_2',
  187. );
  188. field_test_create_bundle($bundles[1]);
  189. field_test_create_bundle($bundles[2]);
  190. // Define 3 fields:
  191. // - field_1 is in bundle_1 and bundle_2,
  192. // - field_2 is in bundle_1,
  193. // - field_3 is in bundle_2.
  194. $field_bundles_map = array(
  195. 1 => array(1, 2),
  196. 2 => array(1),
  197. 3 => array(2),
  198. );
  199. for ($i = 1; $i <= 3; $i++) {
  200. $field_names[$i] = 'field_' . $i;
  201. $field = array('field_name' => $field_names[$i], 'type' => 'test_field');
  202. $field = field_create_field($field);
  203. $field_ids[$i] = $field['id'];
  204. foreach ($field_bundles_map[$i] as $bundle) {
  205. $instance = array(
  206. 'field_name' => $field_names[$i],
  207. 'entity_type' => 'test_entity',
  208. 'bundle' => $bundles[$bundle],
  209. 'settings' => array(
  210. // Configure the instance so that we test hook_field_load()
  211. // (see field_test_field_load() in field_test.module).
  212. 'test_hook_field_load' => TRUE,
  213. ),
  214. );
  215. field_create_instance($instance);
  216. }
  217. }
  218. // Create one test entity per bundle, with random values.
  219. foreach ($bundles as $index => $bundle) {
  220. $entities[$index] = field_test_create_stub_entity($index, $index, $bundle);
  221. $entity = clone($entities[$index]);
  222. $instances = field_info_instances('test_entity', $bundle);
  223. foreach ($instances as $field_name => $instance) {
  224. $values[$index][$field_name] = mt_rand(1, 127);
  225. $entity->$field_name = array($langcode => array(array('value' => $values[$index][$field_name])));
  226. }
  227. field_attach_insert($entity_type, $entity);
  228. }
  229. // Check that a single load correctly loads field values for both entities.
  230. field_attach_load($entity_type, $entities);
  231. foreach ($entities as $index => $entity) {
  232. $instances = field_info_instances($entity_type, $bundles[$index]);
  233. foreach ($instances as $field_name => $instance) {
  234. // The field value loaded matches the one inserted.
  235. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], $values[$index][$field_name], t('Entity %index: expected value was found.', array('%index' => $index)));
  236. // The value added in hook_field_load() is found.
  237. $this->assertEqual($entity->{$field_name}[$langcode][0]['additional_key'], 'additional_value', t('Entity %index: extra information was found', array('%index' => $index)));
  238. }
  239. }
  240. // Check that the single-field load option works.
  241. $entity = field_test_create_stub_entity(1, 1, $bundles[1]);
  242. field_attach_load($entity_type, array(1 => $entity), FIELD_LOAD_CURRENT, array('field_id' => $field_ids[1]));
  243. $this->assertEqual($entity->{$field_names[1]}[$langcode][0]['value'], $values[1][$field_names[1]], t('Entity %index: expected value was found.', array('%index' => 1)));
  244. $this->assertEqual($entity->{$field_names[1]}[$langcode][0]['additional_key'], 'additional_value', t('Entity %index: extra information was found', array('%index' => 1)));
  245. $this->assert(!isset($entity->{$field_names[2]}), t('Entity %index: field %field_name is not loaded.', array('%index' => 2, '%field_name' => $field_names[2])));
  246. $this->assert(!isset($entity->{$field_names[3]}), t('Entity %index: field %field_name is not loaded.', array('%index' => 3, '%field_name' => $field_names[3])));
  247. }
  248. /**
  249. * Test saving and loading fields using different storage backends.
  250. */
  251. function testFieldAttachSaveLoadDifferentStorage() {
  252. $entity_type = 'test_entity';
  253. $langcode = LANGUAGE_NONE;
  254. // Create two fields using different storage backends, and their instances.
  255. $fields = array(
  256. array(
  257. 'field_name' => 'field_1',
  258. 'type' => 'test_field',
  259. 'cardinality' => 4,
  260. 'storage' => array('type' => 'field_sql_storage')
  261. ),
  262. array(
  263. 'field_name' => 'field_2',
  264. 'type' => 'test_field',
  265. 'cardinality' => 4,
  266. 'storage' => array('type' => 'field_test_storage')
  267. ),
  268. );
  269. foreach ($fields as $field) {
  270. field_create_field($field);
  271. $instance = array(
  272. 'field_name' => $field['field_name'],
  273. 'entity_type' => 'test_entity',
  274. 'bundle' => 'test_bundle',
  275. );
  276. field_create_instance($instance);
  277. }
  278. $entity_init = field_test_create_stub_entity();
  279. // Create entity and insert random values.
  280. $entity = clone($entity_init);
  281. $values = array();
  282. foreach ($fields as $field) {
  283. $values[$field['field_name']] = $this->_generateTestFieldValues($this->field['cardinality']);
  284. $entity->{$field['field_name']}[$langcode] = $values[$field['field_name']];
  285. }
  286. field_attach_insert($entity_type, $entity);
  287. // Check that values are loaded as expected.
  288. $entity = clone($entity_init);
  289. field_attach_load($entity_type, array($entity->ftid => $entity));
  290. foreach ($fields as $field) {
  291. $this->assertEqual($values[$field['field_name']], $entity->{$field['field_name']}[$langcode], t('%storage storage: expected values were found.', array('%storage' => $field['storage']['type'])));
  292. }
  293. }
  294. /**
  295. * Test storage details alteration.
  296. *
  297. * @see field_test_storage_details_alter()
  298. */
  299. function testFieldStorageDetailsAlter() {
  300. $field_name = 'field_test_change_my_details';
  301. $field = array(
  302. 'field_name' => $field_name,
  303. 'type' => 'test_field',
  304. 'cardinality' => 4,
  305. 'storage' => array('type' => 'field_test_storage'),
  306. );
  307. $field = field_create_field($field);
  308. $instance = array(
  309. 'field_name' => $field_name,
  310. 'entity_type' => 'test_entity',
  311. 'bundle' => 'test_bundle',
  312. );
  313. field_create_instance($instance);
  314. $field = field_info_field($instance['field_name']);
  315. $instance = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
  316. // The storage details are indexed by a storage engine type.
  317. $this->assertTrue(array_key_exists('drupal_variables', $field['storage']['details']), t('The storage type is Drupal variables.'));
  318. $details = $field['storage']['details']['drupal_variables'];
  319. // The field_test storage details are indexed by variable name. The details
  320. // are altered, so moon and mars are correct for this test.
  321. $this->assertTrue(array_key_exists('moon', $details[FIELD_LOAD_CURRENT]), t('Moon is available in the instance array.'));
  322. $this->assertTrue(array_key_exists('mars', $details[FIELD_LOAD_REVISION]), t('Mars is available in the instance array.'));
  323. // Test current and revision storage details together because the columns
  324. // are the same.
  325. foreach ((array) $field['columns'] as $column_name => $attributes) {
  326. $this->assertEqual($details[FIELD_LOAD_CURRENT]['moon'][$column_name], $column_name, t('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => 'moon[FIELD_LOAD_CURRENT]')));
  327. $this->assertEqual($details[FIELD_LOAD_REVISION]['mars'][$column_name], $column_name, t('Column name %value matches the definition in %bin.', array('%value' => $column_name, '%bin' => 'mars[FIELD_LOAD_REVISION]')));
  328. }
  329. }
  330. /**
  331. * Tests insert and update with missing or NULL fields.
  332. */
  333. function testFieldAttachSaveMissingData() {
  334. $entity_type = 'test_entity';
  335. $entity_init = field_test_create_stub_entity();
  336. $langcode = LANGUAGE_NONE;
  337. // Insert: Field is missing.
  338. $entity = clone($entity_init);
  339. field_attach_insert($entity_type, $entity);
  340. $entity = clone($entity_init);
  341. field_attach_load($entity_type, array($entity->ftid => $entity));
  342. $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: missing field results in no value saved'));
  343. // Insert: Field is NULL.
  344. field_cache_clear();
  345. $entity = clone($entity_init);
  346. $entity->{$this->field_name} = NULL;
  347. field_attach_insert($entity_type, $entity);
  348. $entity = clone($entity_init);
  349. field_attach_load($entity_type, array($entity->ftid => $entity));
  350. $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: NULL field results in no value saved'));
  351. // Add some real data.
  352. field_cache_clear();
  353. $entity = clone($entity_init);
  354. $values = $this->_generateTestFieldValues(1);
  355. $entity->{$this->field_name}[$langcode] = $values;
  356. field_attach_insert($entity_type, $entity);
  357. $entity = clone($entity_init);
  358. field_attach_load($entity_type, array($entity->ftid => $entity));
  359. $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Field data saved'));
  360. // Update: Field is missing. Data should survive.
  361. field_cache_clear();
  362. $entity = clone($entity_init);
  363. field_attach_update($entity_type, $entity);
  364. $entity = clone($entity_init);
  365. field_attach_load($entity_type, array($entity->ftid => $entity));
  366. $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Update: missing field leaves existing values in place'));
  367. // Update: Field is NULL. Data should be wiped.
  368. field_cache_clear();
  369. $entity = clone($entity_init);
  370. $entity->{$this->field_name} = NULL;
  371. field_attach_update($entity_type, $entity);
  372. $entity = clone($entity_init);
  373. field_attach_load($entity_type, array($entity->ftid => $entity));
  374. $this->assertTrue(empty($entity->{$this->field_name}), t('Update: NULL field removes existing values'));
  375. // Re-add some data.
  376. field_cache_clear();
  377. $entity = clone($entity_init);
  378. $values = $this->_generateTestFieldValues(1);
  379. $entity->{$this->field_name}[$langcode] = $values;
  380. field_attach_update($entity_type, $entity);
  381. $entity = clone($entity_init);
  382. field_attach_load($entity_type, array($entity->ftid => $entity));
  383. $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Field data saved'));
  384. // Update: Field is empty array. Data should be wiped.
  385. field_cache_clear();
  386. $entity = clone($entity_init);
  387. $entity->{$this->field_name} = array();
  388. field_attach_update($entity_type, $entity);
  389. $entity = clone($entity_init);
  390. field_attach_load($entity_type, array($entity->ftid => $entity));
  391. $this->assertTrue(empty($entity->{$this->field_name}), t('Update: empty array removes existing values'));
  392. }
  393. /**
  394. * Test insert with missing or NULL fields, with default value.
  395. */
  396. function testFieldAttachSaveMissingDataDefaultValue() {
  397. // Add a default value function.
  398. $this->instance['default_value_function'] = 'field_test_default_value';
  399. field_update_instance($this->instance);
  400. $entity_type = 'test_entity';
  401. $entity_init = field_test_create_stub_entity();
  402. $langcode = LANGUAGE_NONE;
  403. // Insert: Field is NULL.
  404. $entity = clone($entity_init);
  405. $entity->{$this->field_name}[$langcode] = NULL;
  406. field_attach_insert($entity_type, $entity);
  407. $entity = clone($entity_init);
  408. field_attach_load($entity_type, array($entity->ftid => $entity));
  409. $this->assertTrue(empty($entity->{$this->field_name}[$langcode]), t('Insert: NULL field results in no value saved'));
  410. // Insert: Field is missing.
  411. field_cache_clear();
  412. $entity = clone($entity_init);
  413. field_attach_insert($entity_type, $entity);
  414. $entity = clone($entity_init);
  415. field_attach_load($entity_type, array($entity->ftid => $entity));
  416. $values = field_test_default_value($entity_type, $entity, $this->field, $this->instance);
  417. $this->assertEqual($entity->{$this->field_name}[$langcode], $values, t('Insert: missing field results in default value saved'));
  418. }
  419. /**
  420. * Test field_attach_delete().
  421. */
  422. function testFieldAttachDelete() {
  423. $entity_type = 'test_entity';
  424. $langcode = LANGUAGE_NONE;
  425. $rev[0] = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  426. // Create revision 0
  427. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  428. $rev[0]->{$this->field_name}[$langcode] = $values;
  429. field_attach_insert($entity_type, $rev[0]);
  430. // Create revision 1
  431. $rev[1] = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
  432. $rev[1]->{$this->field_name}[$langcode] = $values;
  433. field_attach_update($entity_type, $rev[1]);
  434. // Create revision 2
  435. $rev[2] = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
  436. $rev[2]->{$this->field_name}[$langcode] = $values;
  437. field_attach_update($entity_type, $rev[2]);
  438. // Confirm each revision loads
  439. foreach (array_keys($rev) as $vid) {
  440. $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
  441. field_attach_load_revision($entity_type, array(0 => $read));
  442. $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
  443. }
  444. // Delete revision 1, confirm the other two still load.
  445. field_attach_delete_revision($entity_type, $rev[1]);
  446. foreach (array(0, 2) as $vid) {
  447. $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
  448. field_attach_load_revision($entity_type, array(0 => $read));
  449. $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
  450. }
  451. // Confirm the current revision still loads
  452. $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
  453. field_attach_load($entity_type, array(0 => $read));
  454. $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity current revision has {$this->field['cardinality']} values.");
  455. // Delete all field data, confirm nothing loads
  456. field_attach_delete($entity_type, $rev[2]);
  457. foreach (array(0, 1, 2) as $vid) {
  458. $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
  459. field_attach_load_revision($entity_type, array(0 => $read));
  460. $this->assertIdentical($read->{$this->field_name}, array(), "The test entity revision $vid is deleted.");
  461. }
  462. $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
  463. field_attach_load($entity_type, array(0 => $read));
  464. $this->assertIdentical($read->{$this->field_name}, array(), t('The test entity current revision is deleted.'));
  465. }
  466. /**
  467. * Test field_attach_create_bundle() and field_attach_rename_bundle().
  468. */
  469. function testFieldAttachCreateRenameBundle() {
  470. // Create a new bundle. This has to be initiated by the module so that its
  471. // hook_entity_info() is consistent.
  472. $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
  473. field_test_create_bundle($new_bundle);
  474. // Add an instance to that bundle.
  475. $this->instance['bundle'] = $new_bundle;
  476. field_create_instance($this->instance);
  477. // Save an entity with data in the field.
  478. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  479. $langcode = LANGUAGE_NONE;
  480. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  481. $entity->{$this->field_name}[$langcode] = $values;
  482. $entity_type = 'test_entity';
  483. field_attach_insert($entity_type, $entity);
  484. // Verify the field data is present on load.
  485. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  486. field_attach_load($entity_type, array(0 => $entity));
  487. $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Data is retrieved for the new bundle");
  488. // Rename the bundle. This has to be initiated by the module so that its
  489. // hook_entity_info() is consistent.
  490. $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
  491. field_test_rename_bundle($this->instance['bundle'], $new_bundle);
  492. // Check that the instance definition has been updated.
  493. $this->instance = field_info_instance($entity_type, $this->field_name, $new_bundle);
  494. $this->assertIdentical($this->instance['bundle'], $new_bundle, "Bundle name has been updated in the instance.");
  495. // Verify the field data is present on load.
  496. $entity = field_test_create_stub_entity(0, 0, $new_bundle);
  497. field_attach_load($entity_type, array(0 => $entity));
  498. $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Bundle name has been updated in the field storage");
  499. }
  500. /**
  501. * Test field_attach_delete_bundle().
  502. */
  503. function testFieldAttachDeleteBundle() {
  504. // Create a new bundle. This has to be initiated by the module so that its
  505. // hook_entity_info() is consistent.
  506. $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
  507. field_test_create_bundle($new_bundle);
  508. // Add an instance to that bundle.
  509. $this->instance['bundle'] = $new_bundle;
  510. field_create_instance($this->instance);
  511. // Create a second field for the test bundle
  512. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  513. $field = array('field_name' => $field_name, 'type' => 'test_field', 'cardinality' => 1);
  514. field_create_field($field);
  515. $instance = array(
  516. 'field_name' => $field_name,
  517. 'entity_type' => 'test_entity',
  518. 'bundle' => $this->instance['bundle'],
  519. 'label' => $this->randomName() . '_label',
  520. 'description' => $this->randomName() . '_description',
  521. 'weight' => mt_rand(0, 127),
  522. // test_field has no instance settings
  523. 'widget' => array(
  524. 'type' => 'test_field_widget',
  525. 'settings' => array(
  526. 'size' => mt_rand(0, 255))));
  527. field_create_instance($instance);
  528. // Save an entity with data for both fields
  529. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  530. $langcode = LANGUAGE_NONE;
  531. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  532. $entity->{$this->field_name}[$langcode] = $values;
  533. $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues(1);
  534. field_attach_insert('test_entity', $entity);
  535. // Verify the fields are present on load
  536. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  537. field_attach_load('test_entity', array(0 => $entity));
  538. $this->assertEqual(count($entity->{$this->field_name}[$langcode]), 4, 'First field got loaded');
  539. $this->assertEqual(count($entity->{$field_name}[$langcode]), 1, 'Second field got loaded');
  540. // Delete the bundle. This has to be initiated by the module so that its
  541. // hook_entity_info() is consistent.
  542. field_test_delete_bundle($this->instance['bundle']);
  543. // Verify no data gets loaded
  544. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  545. field_attach_load('test_entity', array(0 => $entity));
  546. $this->assertFalse(isset($entity->{$this->field_name}[$langcode]), 'No data for first field');
  547. $this->assertFalse(isset($entity->{$field_name}[$langcode]), 'No data for second field');
  548. // Verify that the instances are gone
  549. $this->assertFalse(field_read_instance('test_entity', $this->field_name, $this->instance['bundle']), "First field is deleted");
  550. $this->assertFalse(field_read_instance('test_entity', $field_name, $instance['bundle']), "Second field is deleted");
  551. }
  552. }
  553. /**
  554. * Unit test class for non-storage related field_attach_* functions.
  555. */
  556. class FieldAttachOtherTestCase extends FieldAttachTestCase {
  557. public static function getInfo() {
  558. return array(
  559. 'name' => 'Field attach tests (other)',
  560. 'description' => 'Test other Field Attach API functions.',
  561. 'group' => 'Field API',
  562. );
  563. }
  564. /**
  565. * Test field_attach_view() and field_attach_prepare_view().
  566. */
  567. function testFieldAttachView() {
  568. $entity_type = 'test_entity';
  569. $entity_init = field_test_create_stub_entity();
  570. $langcode = LANGUAGE_NONE;
  571. // Populate values to be displayed.
  572. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  573. $entity_init->{$this->field_name}[$langcode] = $values;
  574. // Simple formatter, label displayed.
  575. $entity = clone($entity_init);
  576. $formatter_setting = $this->randomName();
  577. $this->instance['display'] = array(
  578. 'full' => array(
  579. 'label' => 'above',
  580. 'type' => 'field_test_default',
  581. 'settings' => array(
  582. 'test_formatter_setting' => $formatter_setting,
  583. )
  584. ),
  585. );
  586. field_update_instance($this->instance);
  587. field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
  588. $entity->content = field_attach_view($entity_type, $entity, 'full');
  589. $output = drupal_render($entity->content);
  590. $this->content = $output;
  591. $this->assertRaw($this->instance['label'], "Label is displayed.");
  592. foreach ($values as $delta => $value) {
  593. $this->content = $output;
  594. $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
  595. }
  596. // Label hidden.
  597. $entity = clone($entity_init);
  598. $this->instance['display']['full']['label'] = 'hidden';
  599. field_update_instance($this->instance);
  600. field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
  601. $entity->content = field_attach_view($entity_type, $entity, 'full');
  602. $output = drupal_render($entity->content);
  603. $this->content = $output;
  604. $this->assertNoRaw($this->instance['label'], "Hidden label: label is not displayed.");
  605. // Field hidden.
  606. $entity = clone($entity_init);
  607. $this->instance['display'] = array(
  608. 'full' => array(
  609. 'label' => 'above',
  610. 'type' => 'hidden',
  611. ),
  612. );
  613. field_update_instance($this->instance);
  614. field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
  615. $entity->content = field_attach_view($entity_type, $entity, 'full');
  616. $output = drupal_render($entity->content);
  617. $this->content = $output;
  618. $this->assertNoRaw($this->instance['label'], "Hidden field: label is not displayed.");
  619. foreach ($values as $delta => $value) {
  620. $this->assertNoRaw($value['value'], "Hidden field: value $delta is not displayed.");
  621. }
  622. // Multiple formatter.
  623. $entity = clone($entity_init);
  624. $formatter_setting = $this->randomName();
  625. $this->instance['display'] = array(
  626. 'full' => array(
  627. 'label' => 'above',
  628. 'type' => 'field_test_multiple',
  629. 'settings' => array(
  630. 'test_formatter_setting_multiple' => $formatter_setting,
  631. )
  632. ),
  633. );
  634. field_update_instance($this->instance);
  635. field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
  636. $entity->content = field_attach_view($entity_type, $entity, 'full');
  637. $output = drupal_render($entity->content);
  638. $display = $formatter_setting;
  639. foreach ($values as $delta => $value) {
  640. $display .= "|$delta:{$value['value']}";
  641. }
  642. $this->content = $output;
  643. $this->assertRaw($display, "Multiple formatter: all values are displayed, formatter settings are applied.");
  644. // Test a formatter that uses hook_field_formatter_prepare_view().
  645. $entity = clone($entity_init);
  646. $formatter_setting = $this->randomName();
  647. $this->instance['display'] = array(
  648. 'full' => array(
  649. 'label' => 'above',
  650. 'type' => 'field_test_with_prepare_view',
  651. 'settings' => array(
  652. 'test_formatter_setting_additional' => $formatter_setting,
  653. )
  654. ),
  655. );
  656. field_update_instance($this->instance);
  657. field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
  658. $entity->content = field_attach_view($entity_type, $entity, 'full');
  659. $output = drupal_render($entity->content);
  660. $this->content = $output;
  661. foreach ($values as $delta => $value) {
  662. $this->content = $output;
  663. $expected = $formatter_setting . '|' . $value['value'] . '|' . ($value['value'] + 1);
  664. $this->assertRaw($expected, "Value $delta is displayed, formatter settings are applied.");
  665. }
  666. // TODO:
  667. // - check display order with several fields
  668. // Preprocess template.
  669. $variables = array();
  670. field_attach_preprocess($entity_type, $entity, $entity->content, $variables);
  671. $result = TRUE;
  672. foreach ($values as $delta => $item) {
  673. if ($variables[$this->field_name][$delta]['value'] !== $item['value']) {
  674. $result = FALSE;
  675. break;
  676. }
  677. }
  678. $this->assertTrue($result, t('Variable $@field_name correctly populated.', array('@field_name' => $this->field_name)));
  679. }
  680. /**
  681. * Tests the 'multiple entity' behavior of field_attach_prepare_view().
  682. */
  683. function testFieldAttachPrepareViewMultiple() {
  684. $entity_type = 'test_entity';
  685. $langcode = LANGUAGE_NONE;
  686. // Set the instance to be hidden.
  687. $this->instance['display']['full']['type'] = 'hidden';
  688. field_update_instance($this->instance);
  689. // Set up a second instance on another bundle, with a formatter that uses
  690. // hook_field_formatter_prepare_view().
  691. field_test_create_bundle('test_bundle_2');
  692. $formatter_setting = $this->randomName();
  693. $this->instance2 = $this->instance;
  694. $this->instance2['bundle'] = 'test_bundle_2';
  695. $this->instance2['display']['full'] = array(
  696. 'type' => 'field_test_with_prepare_view',
  697. 'settings' => array(
  698. 'test_formatter_setting_additional' => $formatter_setting,
  699. )
  700. );
  701. field_create_instance($this->instance2);
  702. // Create one entity in each bundle.
  703. $entity1_init = field_test_create_stub_entity(1, 1, 'test_bundle');
  704. $values1 = $this->_generateTestFieldValues($this->field['cardinality']);
  705. $entity1_init->{$this->field_name}[$langcode] = $values1;
  706. $entity2_init = field_test_create_stub_entity(2, 2, 'test_bundle_2');
  707. $values2 = $this->_generateTestFieldValues($this->field['cardinality']);
  708. $entity2_init->{$this->field_name}[$langcode] = $values2;
  709. // Run prepare_view, and check that the entities come out as expected.
  710. $entity1 = clone($entity1_init);
  711. $entity2 = clone($entity2_init);
  712. field_attach_prepare_view($entity_type, array($entity1->ftid => $entity1, $entity2->ftid => $entity2), 'full');
  713. $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
  714. $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
  715. // Same thing, reversed order.
  716. $entity1 = clone($entity1_init);
  717. $entity2 = clone($entity2_init);
  718. field_attach_prepare_view($entity_type, array($entity2->ftid => $entity2, $entity1->ftid => $entity1), 'full');
  719. $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
  720. $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
  721. }
  722. /**
  723. * Test field cache.
  724. */
  725. function testFieldAttachCache() {
  726. // Initialize random values and a test entity.
  727. $entity_init = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
  728. $langcode = LANGUAGE_NONE;
  729. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  730. // Non-cacheable entity type.
  731. $entity_type = 'test_entity';
  732. $cid = "field:$entity_type:{$entity_init->ftid}";
  733. // Check that no initial cache entry is present.
  734. $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no initial cache entry'));
  735. // Save, and check that no cache entry is present.
  736. $entity = clone($entity_init);
  737. $entity->{$this->field_name}[$langcode] = $values;
  738. field_attach_insert($entity_type, $entity);
  739. $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on insert'));
  740. // Load, and check that no cache entry is present.
  741. $entity = clone($entity_init);
  742. field_attach_load($entity_type, array($entity->ftid => $entity));
  743. $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on load'));
  744. // Cacheable entity type.
  745. $entity_type = 'test_cacheable_entity';
  746. $cid = "field:$entity_type:{$entity_init->ftid}";
  747. $instance = $this->instance;
  748. $instance['entity_type'] = $entity_type;
  749. field_create_instance($instance);
  750. // Check that no initial cache entry is present.
  751. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no initial cache entry'));
  752. // Save, and check that no cache entry is present.
  753. $entity = clone($entity_init);
  754. $entity->{$this->field_name}[$langcode] = $values;
  755. field_attach_insert($entity_type, $entity);
  756. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on insert'));
  757. // Load a single field, and check that no cache entry is present.
  758. $entity = clone($entity_init);
  759. field_attach_load($entity_type, array($entity->ftid => $entity), FIELD_LOAD_CURRENT, array('field_id' => $this->field_id));
  760. $cache = cache_get($cid, 'cache_field');
  761. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on loading a single field'));
  762. // Load, and check that a cache entry is present with the expected values.
  763. $entity = clone($entity_init);
  764. field_attach_load($entity_type, array($entity->ftid => $entity));
  765. $cache = cache_get($cid, 'cache_field');
  766. $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));
  767. // Update with different values, and check that the cache entry is wiped.
  768. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  769. $entity = clone($entity_init);
  770. $entity->{$this->field_name}[$langcode] = $values;
  771. field_attach_update($entity_type, $entity);
  772. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on update'));
  773. // Load, and check that a cache entry is present with the expected values.
  774. $entity = clone($entity_init);
  775. field_attach_load($entity_type, array($entity->ftid => $entity));
  776. $cache = cache_get($cid, 'cache_field');
  777. $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));
  778. // Create a new revision, and check that the cache entry is wiped.
  779. $entity_init = field_test_create_stub_entity(1, 2, $this->instance['bundle']);
  780. $values = $this->_generateTestFieldValues($this->field['cardinality']);
  781. $entity = clone($entity_init);
  782. $entity->{$this->field_name}[$langcode] = $values;
  783. field_attach_update($entity_type, $entity);
  784. $cache = cache_get($cid, 'cache_field');
  785. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on new revision creation'));
  786. // Load, and check that a cache entry is present with the expected values.
  787. $entity = clone($entity_init);
  788. field_attach_load($entity_type, array($entity->ftid => $entity));
  789. $cache = cache_get($cid, 'cache_field');
  790. $this->assertEqual($cache->data[$this->field_name][$langcode], $values, t('Cached: correct cache entry on load'));
  791. // Delete, and check that the cache entry is wiped.
  792. field_attach_delete($entity_type, $entity);
  793. $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry after delete'));
  794. }
  795. /**
  796. * Test field_attach_validate().
  797. *
  798. * Verify that field_attach_validate() invokes the correct
  799. * hook_field_validate.
  800. */
  801. function testFieldAttachValidate() {
  802. $entity_type = 'test_entity';
  803. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  804. $langcode = LANGUAGE_NONE;
  805. // Set up values to generate errors
  806. $values = array();
  807. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  808. $values[$delta]['value'] = -1;
  809. }
  810. // Arrange for item 1 not to generate an error
  811. $values[1]['value'] = 1;
  812. $entity->{$this->field_name}[$langcode] = $values;
  813. try {
  814. field_attach_validate($entity_type, $entity);
  815. }
  816. catch (FieldValidationException $e) {
  817. $errors = $e->errors;
  818. }
  819. foreach ($values as $delta => $value) {
  820. if ($value['value'] != 1) {
  821. $this->assertIdentical($errors[$this->field_name][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on value $delta");
  822. $this->assertEqual(count($errors[$this->field_name][$langcode][$delta]), 1, "Only one error set on value $delta");
  823. unset($errors[$this->field_name][$langcode][$delta]);
  824. }
  825. else {
  826. $this->assertFalse(isset($errors[$this->field_name][$langcode][$delta]), "No error set on value $delta");
  827. }
  828. }
  829. $this->assertEqual(count($errors[$this->field_name][$langcode]), 0, 'No extraneous errors set');
  830. // Check that cardinality is validated.
  831. $entity->{$this->field_name}[$langcode] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
  832. try {
  833. field_attach_validate($entity_type, $entity);
  834. }
  835. catch (FieldValidationException $e) {
  836. $errors = $e->errors;
  837. }
  838. $this->assertEqual($errors[$this->field_name][$langcode][0][0]['error'], 'field_cardinality', t('Cardinality validation failed.'));
  839. }
  840. /**
  841. * Test field_attach_form().
  842. *
  843. * This could be much more thorough, but it does verify that the correct
  844. * widgets show up.
  845. */
  846. function testFieldAttachForm() {
  847. $entity_type = 'test_entity';
  848. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  849. $form = array();
  850. $form_state = form_state_defaults();
  851. field_attach_form($entity_type, $entity, $form, $form_state);
  852. $langcode = LANGUAGE_NONE;
  853. $this->assertEqual($form[$this->field_name][$langcode]['#title'], $this->instance['label'], "Form title is {$this->instance['label']}");
  854. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  855. // field_test_widget uses 'textfield'
  856. $this->assertEqual($form[$this->field_name][$langcode][$delta]['value']['#type'], 'textfield', "Form delta $delta widget is textfield");
  857. }
  858. }
  859. /**
  860. * Test field_attach_submit().
  861. */
  862. function testFieldAttachSubmit() {
  863. $entity_type = 'test_entity';
  864. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  865. // Build the form.
  866. $form = array();
  867. $form_state = form_state_defaults();
  868. field_attach_form($entity_type, $entity, $form, $form_state);
  869. // Simulate incoming values.
  870. $values = array();
  871. $weights = array();
  872. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  873. $values[$delta]['value'] = mt_rand(1, 127);
  874. // Assign random weight.
  875. do {
  876. $weight = mt_rand(0, $this->field['cardinality']);
  877. } while (in_array($weight, $weights));
  878. $weights[$delta] = $weight;
  879. $values[$delta]['_weight'] = $weight;
  880. }
  881. // Leave an empty value. 'field_test' fields are empty if empty().
  882. $values[1]['value'] = 0;
  883. $langcode = LANGUAGE_NONE;
  884. // Pretend the form has been built.
  885. drupal_prepare_form('field_test_entity_form', $form, $form_state);
  886. drupal_process_form('field_test_entity_form', $form, $form_state);
  887. $form_state['values'][$this->field_name][$langcode] = $values;
  888. field_attach_submit($entity_type, $entity, $form, $form_state);
  889. asort($weights);
  890. $expected_values = array();
  891. foreach ($weights as $key => $value) {
  892. if ($key != 1) {
  893. $expected_values[] = array('value' => $values[$key]['value']);
  894. }
  895. }
  896. $this->assertIdentical($entity->{$this->field_name}[$langcode], $expected_values, 'Submit filters empty values');
  897. }
  898. }
  899. class FieldInfoTestCase extends FieldTestCase {
  900. public static function getInfo() {
  901. return array(
  902. 'name' => 'Field info tests',
  903. 'description' => 'Get information about existing fields, instances and bundles.',
  904. 'group' => 'Field API',
  905. );
  906. }
  907. function setUp() {
  908. parent::setUp('field_test');
  909. }
  910. /**
  911. * Test that field types and field definitions are correcly cached.
  912. */
  913. function testFieldInfo() {
  914. // Test that field_test module's fields, widgets, and formatters show up.
  915. $field_test_info = field_test_field_info();
  916. // We need to account for the existence of user_field_info_alter().
  917. foreach (array_keys($field_test_info) as $name) {
  918. $field_test_info[$name]['instance_settings']['user_register_form'] = FALSE;
  919. }
  920. $info = field_info_field_types();
  921. foreach ($field_test_info as $t_key => $field_type) {
  922. foreach ($field_type as $key => $val) {
  923. $this->assertEqual($info[$t_key][$key], $val, t("Field type $t_key key $key is $val"));
  924. }
  925. $this->assertEqual($info[$t_key]['module'], 'field_test', t("Field type field_test module appears"));
  926. }
  927. $formatter_info = field_test_field_formatter_info();
  928. $info = field_info_formatter_types();
  929. foreach ($formatter_info as $f_key => $formatter) {
  930. foreach ($formatter as $key => $val) {
  931. $this->assertEqual($info[$f_key][$key], $val, t("Formatter type $f_key key $key is $val"));
  932. }
  933. $this->assertEqual($info[$f_key]['module'], 'field_test', t("Formatter type field_test module appears"));
  934. }
  935. $widget_info = field_test_field_widget_info();
  936. $info = field_info_widget_types();
  937. foreach ($widget_info as $w_key => $widget) {
  938. foreach ($widget as $key => $val) {
  939. $this->assertEqual($info[$w_key][$key], $val, t("Widget type $w_key key $key is $val"));
  940. }
  941. $this->assertEqual($info[$w_key]['module'], 'field_test', t("Widget type field_test module appears"));
  942. }
  943. $storage_info = field_test_field_storage_info();
  944. $info = field_info_storage_types();
  945. foreach ($storage_info as $s_key => $storage) {
  946. foreach ($storage as $key => $val) {
  947. $this->assertEqual($info[$s_key][$key], $val, t("Storage type $s_key key $key is $val"));
  948. }
  949. $this->assertEqual($info[$s_key]['module'], 'field_test', t("Storage type field_test module appears"));
  950. }
  951. // Verify that no unexpected instances exist.
  952. $instances = field_info_instances('test_entity');
  953. $expected = array('test_bundle' => array());
  954. $this->assertIdentical($instances, $expected, "field_info_instances('test_entity') returns " . var_export($expected, TRUE) . '.');
  955. $instances = field_info_instances('test_entity', 'test_bundle');
  956. $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'test_bundle') returns an empty array.");
  957. // Create a field, verify it shows up.
  958. $core_fields = field_info_fields();
  959. $field = array(
  960. 'field_name' => drupal_strtolower($this->randomName()),
  961. 'type' => 'test_field',
  962. );
  963. field_create_field($field);
  964. $fields = field_info_fields();
  965. $this->assertEqual(count($fields), count($core_fields) + 1, t('One new field exists'));
  966. $this->assertEqual($fields[$field['field_name']]['field_name'], $field['field_name'], t('info fields contains field name'));
  967. $this->assertEqual($fields[$field['field_name']]['type'], $field['type'], t('info fields contains field type'));
  968. $this->assertEqual($fields[$field['field_name']]['module'], 'field_test', t('info fields contains field module'));
  969. $settings = array('test_field_setting' => 'dummy test string');
  970. foreach ($settings as $key => $val) {
  971. $this->assertEqual($fields[$field['field_name']]['settings'][$key], $val, t("Field setting $key has correct default value $val"));
  972. }
  973. $this->assertEqual($fields[$field['field_name']]['cardinality'], 1, t('info fields contains cardinality 1'));
  974. $this->assertEqual($fields[$field['field_name']]['active'], 1, t('info fields contains active 1'));
  975. // Create an instance, verify that it shows up
  976. $instance = array(
  977. 'field_name' => $field['field_name'],
  978. 'entity_type' => 'test_entity',
  979. 'bundle' => 'test_bundle',
  980. 'label' => $this->randomName(),
  981. 'description' => $this->randomName(),
  982. 'weight' => mt_rand(0, 127),
  983. // test_field has no instance settings
  984. 'widget' => array(
  985. 'type' => 'test_field_widget',
  986. 'settings' => array(
  987. 'test_setting' => 999)));
  988. field_create_instance($instance);
  989. $instances = field_info_instances('test_entity', $instance['bundle']);
  990. $this->assertEqual(count($instances), 1, t('One instance shows up in info when attached to a bundle.'));
  991. $this->assertTrue($instance < $instances[$instance['field_name']], t('Instance appears in info correctly'));
  992. // Test a valid entity type but an invalid bundle.
  993. $instances = field_info_instances('test_entity', 'invalid_bundle');
  994. $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'invalid_bundle') returns an empty array.");
  995. // Test invalid entity type and bundle.
  996. $instances = field_info_instances('invalid_entity', $instance['bundle']);
  997. $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity', 'test_bundle') returns an empty array.");
  998. // Test invalid entity type, no bundle provided.
  999. $instances = field_info_instances('invalid_entity');
  1000. $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity') returns an empty array.");
  1001. // Test with an entity type that has no bundles.
  1002. $instances = field_info_instances('user');
  1003. $expected = array('user' => array());
  1004. $this->assertIdentical($instances, $expected, "field_info_instances('user') returns " . var_export($expected, TRUE) . '.');
  1005. $instances = field_info_instances('user', 'user');
  1006. $this->assertIdentical($instances, array(), "field_info_instances('user', 'user') returns an empty array.");
  1007. }
  1008. /**
  1009. * Test that cached field definitions are ready for current runtime context.
  1010. */
  1011. function testFieldPrepare() {
  1012. $field_definition = array(
  1013. 'field_name' => 'field',
  1014. 'type' => 'test_field',
  1015. );
  1016. field_create_field($field_definition);
  1017. // Simulate a stored field definition missing a field setting (e.g. a
  1018. // third-party module adding a new field setting has been enabled, and
  1019. // existing fields do not know the setting yet).
  1020. $data = db_query('SELECT data FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']))->fetchField();
  1021. $data = unserialize($data);
  1022. $data['settings'] = array();
  1023. db_update('field_config')
  1024. ->fields(array('data' => serialize($data)))
  1025. ->condition('field_name', $field_definition['field_name'])
  1026. ->execute();
  1027. field_cache_clear();
  1028. // Read the field back.
  1029. $field = field_info_field($field_definition['field_name']);
  1030. // Check that all expected settings are in place.
  1031. $field_type = field_info_field_types($field_definition['type']);
  1032. $this->assertIdentical($field['settings'], $field_type['settings'], t('All expected default field settings are present.'));
  1033. }
  1034. /**
  1035. * Test that cached instance definitions are ready for current runtime context.
  1036. */
  1037. function testInstancePrepare() {
  1038. $field_definition = array(
  1039. 'field_name' => 'field',
  1040. 'type' => 'test_field',
  1041. );
  1042. field_create_field($field_definition);
  1043. $instance_definition = array(
  1044. 'field_name' => $field_definition['field_name'],
  1045. 'entity_type' => 'test_entity',
  1046. 'bundle' => 'test_bundle',
  1047. );
  1048. field_create_instance($instance_definition);
  1049. // Simulate a stored instance definition missing various settings (e.g. a
  1050. // third-party module adding instance, widget or display settings has been
  1051. // enabled, but existing instances do not know the new settings).
  1052. $data = db_query('SELECT data FROM {field_config_instance} WHERE field_name = :field_name AND bundle = :bundle', array(':field_name' => $instance_definition['field_name'], ':bundle' => $instance_definition['bundle']))->fetchField();
  1053. $data = unserialize($data);
  1054. $data['settings'] = array();
  1055. $data['widget']['settings'] = 'unavailable_widget';
  1056. $data['widget']['settings'] = array();
  1057. $data['display']['default']['type'] = 'unavailable_formatter';
  1058. $data['display']['default']['settings'] = array();
  1059. db_update('field_config_instance')
  1060. ->fields(array('data' => serialize($data)))
  1061. ->condition('field_name', $instance_definition['field_name'])
  1062. ->condition('bundle', $instance_definition['bundle'])
  1063. ->execute();
  1064. field_cache_clear();
  1065. // Read the instance back.
  1066. $instance = field_info_instance($instance_definition['entity_type'], $instance_definition['field_name'], $instance_definition['bundle']);
  1067. // Check that all expected instance settings are in place.
  1068. $field_type = field_info_field_types($field_definition['type']);
  1069. $this->assertIdentical($instance['settings'], $field_type['instance_settings'] , t('All expected instance settings are present.'));
  1070. // Check that the default widget is used and expected settings are in place.
  1071. $this->assertIdentical($instance['widget']['type'], $field_type['default_widget'], t('Unavailable widget replaced with default widget.'));
  1072. $widget_type = field_info_widget_types($instance['widget']['type']);
  1073. $this->assertIdentical($instance['widget']['settings'], $widget_type['settings'] , t('All expected widget settings are present.'));
  1074. // Check that display settings are set for the 'default' mode.
  1075. $display = $instance['display']['default'];
  1076. $this->assertIdentical($display['type'], $field_type['default_formatter'], t("Formatter is set for the 'default' view mode"));
  1077. $formatter_type = field_info_formatter_types($display['type']);
  1078. $this->assertIdentical($display['settings'], $formatter_type['settings'] , t("Formatter settings are set for the 'default' view mode"));
  1079. }
  1080. /**
  1081. * Test that instances on disabled entity types are filtered out.
  1082. */
  1083. function testInstanceDisabledEntityType() {
  1084. // For this test the field type and the entity type must be exposed by
  1085. // different modules.
  1086. $field_definition = array(
  1087. 'field_name' => 'field',
  1088. 'type' => 'test_field',
  1089. );
  1090. field_create_field($field_definition);
  1091. $instance_definition = array(
  1092. 'field_name' => 'field',
  1093. 'entity_type' => 'comment',
  1094. 'bundle' => 'comment_node_article',
  1095. );
  1096. field_create_instance($instance_definition);
  1097. // Disable coment module. This clears field_info cache.
  1098. module_disable(array('comment'));
  1099. $this->assertNull(field_info_instance('comment', 'field', 'comment_node_article'), t('No instances are returned on disabled entity types.'));
  1100. }
  1101. /**
  1102. * Test that the field_info settings convenience functions work.
  1103. */
  1104. function testSettingsInfo() {
  1105. $info = field_test_field_info();
  1106. // We need to account for the existence of user_field_info_alter().
  1107. foreach (array_keys($info) as $name) {
  1108. $info[$name]['instance_settings']['user_register_form'] = FALSE;
  1109. }
  1110. foreach ($info as $type => $data) {
  1111. $this->assertIdentical(field_info_field_settings($type), $data['settings'], "field_info_field_settings returns {$type}'s field settings");
  1112. $this->assertIdentical(field_info_instance_settings($type), $data['instance_settings'], "field_info_field_settings returns {$type}'s field instance settings");
  1113. }
  1114. $info = field_test_field_widget_info();
  1115. foreach ($info as $type => $data) {
  1116. $this->assertIdentical(field_info_widget_settings($type), $data['settings'], "field_info_widget_settings returns {$type}'s widget settings");
  1117. }
  1118. $info = field_test_field_formatter_info();
  1119. foreach ($info as $type => $data) {
  1120. $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], "field_info_formatter_settings returns {$type}'s formatter settings");
  1121. }
  1122. }
  1123. }
  1124. class FieldFormTestCase extends FieldTestCase {
  1125. public static function getInfo() {
  1126. return array(
  1127. 'name' => 'Field form tests',
  1128. 'description' => 'Test Field form handling.',
  1129. 'group' => 'Field API',
  1130. );
  1131. }
  1132. function setUp() {
  1133. parent::setUp('field_test');
  1134. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
  1135. $this->drupalLogin($web_user);
  1136. $this->field_single = array('field_name' => 'field_single', 'type' => 'test_field');
  1137. $this->field_multiple = array('field_name' => 'field_multiple', 'type' => 'test_field', 'cardinality' => 4);
  1138. $this->field_unlimited = array('field_name' => 'field_unlimited', 'type' => 'test_field', 'cardinality' => FIELD_CARDINALITY_UNLIMITED);
  1139. $this->instance = array(
  1140. 'entity_type' => 'test_entity',
  1141. 'bundle' => 'test_bundle',
  1142. 'label' => $this->randomName() . '_label',
  1143. 'description' => $this->randomName() . '_description',
  1144. 'weight' => mt_rand(0, 127),
  1145. 'settings' => array(
  1146. 'test_instance_setting' => $this->randomName(),
  1147. ),
  1148. 'widget' => array(
  1149. 'type' => 'test_field_widget',
  1150. 'label' => 'Test Field',
  1151. 'settings' => array(
  1152. 'test_widget_setting' => $this->randomName(),
  1153. )
  1154. )
  1155. );
  1156. }
  1157. function testFieldFormSingle() {
  1158. $this->field = $this->field_single;
  1159. $this->field_name = $this->field['field_name'];
  1160. $this->instance['field_name'] = $this->field_name;
  1161. field_create_field($this->field);
  1162. field_create_instance($this->instance);
  1163. $langcode = LANGUAGE_NONE;
  1164. // Display creation form.
  1165. $this->drupalGet('test-entity/add/test-bundle');
  1166. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget is displayed');
  1167. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1168. // TODO : check that the widget is populated with default value ?
  1169. // Submit with invalid value (field-level validation).
  1170. $edit = array("{$this->field_name}[$langcode][0][value]" => -1);
  1171. $this->drupalPost(NULL, $edit, t('Save'));
  1172. $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->instance['label'])), 'Field validation fails with invalid input.');
  1173. // TODO : check that the correct field is flagged for error.
  1174. // Create an entity
  1175. $value = mt_rand(1, 127);
  1176. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1177. $this->drupalPost(NULL, $edit, t('Save'));
  1178. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1179. $id = $match[1];
  1180. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1181. $entity = field_test_entity_test_load($id);
  1182. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
  1183. // Display edit form.
  1184. $this->drupalGet('test-entity/manage/' . $id . '/edit');
  1185. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", $value, 'Widget is displayed with the correct default value');
  1186. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1187. // Update the entity.
  1188. $value = mt_rand(1, 127);
  1189. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1190. $this->drupalPost(NULL, $edit, t('Save'));
  1191. $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
  1192. $entity = field_test_entity_test_load($id);
  1193. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was updated');
  1194. // Empty the field.
  1195. $value = '';
  1196. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1197. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1198. $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
  1199. $entity = field_test_entity_test_load($id);
  1200. $this->assertIdentical($entity->{$this->field_name}, array(), 'Field was emptied');
  1201. }
  1202. function testFieldFormSingleRequired() {
  1203. $this->field = $this->field_single;
  1204. $this->field_name = $this->field['field_name'];
  1205. $this->instance['field_name'] = $this->field_name;
  1206. $this->instance['required'] = TRUE;
  1207. field_create_field($this->field);
  1208. field_create_instance($this->instance);
  1209. $langcode = LANGUAGE_NONE;
  1210. // Submit with missing required value.
  1211. $edit = array();
  1212. $this->drupalPost('test-entity/add/test-bundle', $edit, t('Save'));
  1213. $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
  1214. // Create an entity
  1215. $value = mt_rand(1, 127);
  1216. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1217. $this->drupalPost(NULL, $edit, t('Save'));
  1218. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1219. $id = $match[1];
  1220. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1221. $entity = field_test_entity_test_load($id);
  1222. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
  1223. // Edit with missing required value.
  1224. $value = '';
  1225. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1226. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1227. $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
  1228. }
  1229. // function testFieldFormMultiple() {
  1230. // $this->field = $this->field_multiple;
  1231. // $this->field_name = $this->field['field_name'];
  1232. // $this->instance['field_name'] = $this->field_name;
  1233. // field_create_field($this->field);
  1234. // field_create_instance($this->instance);
  1235. // }
  1236. function testFieldFormUnlimited() {
  1237. $this->field = $this->field_unlimited;
  1238. $this->field_name = $this->field['field_name'];
  1239. $this->instance['field_name'] = $this->field_name;
  1240. field_create_field($this->field);
  1241. field_create_instance($this->instance);
  1242. $langcode = LANGUAGE_NONE;
  1243. // Display creation form -> 1 widget.
  1244. $this->drupalGet('test-entity/add/test-bundle');
  1245. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1246. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1247. // Press 'add more' button -> 2 widgets.
  1248. $this->drupalPost(NULL, array(), t('Add another item'));
  1249. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1250. $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
  1251. $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
  1252. // TODO : check that non-field inpurs are preserved ('title')...
  1253. // Yet another time so that we can play with more values -> 3 widgets.
  1254. $this->drupalPost(NULL, array(), t('Add another item'));
  1255. // Prepare values and weights.
  1256. $count = 3;
  1257. $delta_range = $count - 1;
  1258. $values = $weights = $pattern = $expected_values = $edit = array();
  1259. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1260. // Assign unique random values and weights.
  1261. do {
  1262. $value = mt_rand(1, 127);
  1263. } while (in_array($value, $values));
  1264. do {
  1265. $weight = mt_rand(-$delta_range, $delta_range);
  1266. } while (in_array($weight, $weights));
  1267. $edit["$this->field_name[$langcode][$delta][value]"] = $value;
  1268. $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
  1269. // We'll need three slightly different formats to check the values.
  1270. $values[$delta] = $value;
  1271. $weights[$delta] = $weight;
  1272. $field_values[$weight]['value'] = (string) $value;
  1273. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  1274. }
  1275. // Press 'add more' button -> 4 widgets
  1276. $this->drupalPost(NULL, $edit, t('Add another item'));
  1277. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1278. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  1279. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  1280. }
  1281. ksort($pattern);
  1282. $pattern = implode('.*', array_values($pattern));
  1283. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  1284. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
  1285. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
  1286. $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  1287. // Submit the form and create the entity.
  1288. $this->drupalPost(NULL, $edit, t('Save'));
  1289. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1290. $id = $match[1];
  1291. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1292. $entity = field_test_entity_test_load($id);
  1293. ksort($field_values);
  1294. $field_values = array_values($field_values);
  1295. $this->assertIdentical($entity->{$this->field_name}[$langcode], $field_values, 'Field values were saved in the correct order');
  1296. // Display edit form: check that the expected number of widgets is
  1297. // displayed, with correct values change values, reorder, leave an empty
  1298. // value in the middle.
  1299. // Submit: check that the entity is updated with correct values
  1300. // Re-submit: check that the field can be emptied.
  1301. // Test with several multiple fields in a form
  1302. }
  1303. /**
  1304. * Tests widget handling of multiple required radios.
  1305. */
  1306. function testFieldFormMultivalueWithRequiredRadio() {
  1307. // Create a multivalue test field.
  1308. $this->field = $this->field_unlimited;
  1309. $this->field_name = $this->field['field_name'];
  1310. $this->instance['field_name'] = $this->field_name;
  1311. field_create_field($this->field);
  1312. field_create_instance($this->instance);
  1313. $langcode = LANGUAGE_NONE;
  1314. // Add a required radio field.
  1315. field_create_field(array(
  1316. 'field_name' => 'required_radio_test',
  1317. 'type' => 'list_text',
  1318. 'settings' => array(
  1319. 'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
  1320. ),
  1321. ));
  1322. field_create_instance(array(
  1323. 'field_name' => 'required_radio_test',
  1324. 'entity_type' => 'test_entity',
  1325. 'bundle' => 'test_bundle',
  1326. 'required' => TRUE,
  1327. 'widget' => array(
  1328. 'type' => 'options_buttons',
  1329. ),
  1330. ));
  1331. // Display creation form.
  1332. $this->drupalGet('test-entity/add/test-bundle');
  1333. // Press the 'Add more' button.
  1334. $this->drupalPost(NULL, array(), t('Add another item'));
  1335. // Verify that no error is thrown by the radio element.
  1336. $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
  1337. // Verify that the widget is added.
  1338. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1339. $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
  1340. $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
  1341. }
  1342. function testFieldFormJSAddMore() {
  1343. $this->field = $this->field_unlimited;
  1344. $this->field_name = $this->field['field_name'];
  1345. $this->instance['field_name'] = $this->field_name;
  1346. field_create_field($this->field);
  1347. field_create_instance($this->instance);
  1348. $langcode = LANGUAGE_NONE;
  1349. // Display creation form -> 1 widget.
  1350. $this->drupalGet('test-entity/add/test-bundle');
  1351. // Press 'add more' button a couple times -> 3 widgets.
  1352. // drupalPostAJAX() will not work iteratively, so we add those through
  1353. // non-JS submission.
  1354. $this->drupalPost(NULL, array(), t('Add another item'));
  1355. $this->drupalPost(NULL, array(), t('Add another item'));
  1356. // Prepare values and weights.
  1357. $count = 3;
  1358. $delta_range = $count - 1;
  1359. $values = $weights = $pattern = $expected_values = $edit = array();
  1360. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1361. // Assign unique random values and weights.
  1362. do {
  1363. $value = mt_rand(1, 127);
  1364. } while (in_array($value, $values));
  1365. do {
  1366. $weight = mt_rand(-$delta_range, $delta_range);
  1367. } while (in_array($weight, $weights));
  1368. $edit["$this->field_name[$langcode][$delta][value]"] = $value;
  1369. $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
  1370. // We'll need three slightly different formats to check the values.
  1371. $values[$delta] = $value;
  1372. $weights[$delta] = $weight;
  1373. $field_values[$weight]['value'] = (string) $value;
  1374. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  1375. }
  1376. // Press 'add more' button through Ajax, and place the expected HTML result
  1377. // as the tested content.
  1378. $commands = $this->drupalPostAJAX(NULL, $edit, $this->field_name . '_add_more');
  1379. $this->content = $commands[1]['data'];
  1380. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1381. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  1382. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  1383. }
  1384. ksort($pattern);
  1385. $pattern = implode('.*', array_values($pattern));
  1386. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  1387. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
  1388. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
  1389. $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  1390. }
  1391. /**
  1392. * Tests widgets handling multiple values.
  1393. */
  1394. function testFieldFormMultipleWidget() {
  1395. // Create a field with fixed cardinality and an instance using a multiple
  1396. // widget.
  1397. $this->field = $this->field_multiple;
  1398. $this->field_name = $this->field['field_name'];
  1399. $this->instance['field_name'] = $this->field_name;
  1400. $this->instance['widget']['type'] = 'test_field_widget_multiple';
  1401. field_create_field($this->field);
  1402. field_create_instance($this->instance);
  1403. $langcode = LANGUAGE_NONE;
  1404. // Display creation form.
  1405. $this->drupalGet('test-entity/add/test-bundle');
  1406. $this->assertFieldByName("{$this->field_name}[$langcode]", '', t('Widget is displayed.'));
  1407. // Create entity with three values.
  1408. $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3');
  1409. $this->drupalPost(NULL, $edit, t('Save'));
  1410. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1411. $id = $match[1];
  1412. // Check that the values were saved.
  1413. $entity_init = field_test_create_stub_entity($id);
  1414. $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
  1415. // Display the form, check that the values are correctly filled in.
  1416. $this->drupalGet('test-entity/manage/' . $id . '/edit');
  1417. $this->assertFieldByName("{$this->field_name}[$langcode]", '1, 2, 3', t('Widget is displayed.'));
  1418. // Submit the form with more values than the field accepts.
  1419. $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3, 4, 5');
  1420. $this->drupalPost(NULL, $edit, t('Save'));
  1421. $this->assertRaw('this field cannot hold more than 4 values', t('Form validation failed.'));
  1422. // Check that the field values were not submitted.
  1423. $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
  1424. }
  1425. /**
  1426. * Tests fields with no 'edit' access.
  1427. */
  1428. function testFieldFormAccess() {
  1429. // Create a "regular" field.
  1430. $field = $this->field_single;
  1431. $field_name = $field['field_name'];
  1432. $instance = $this->instance;
  1433. $instance['field_name'] = $field_name;
  1434. field_create_field($field);
  1435. field_create_instance($instance);
  1436. // Create a field with no edit access - see field_test_field_access().
  1437. $field_no_access = array(
  1438. 'field_name' => 'field_no_edit_access',
  1439. 'type' => 'test_field',
  1440. );
  1441. $field_name_no_access = $field_no_access['field_name'];
  1442. $instance_no_access = array(
  1443. 'field_name' => $field_name_no_access,
  1444. 'entity_type' => 'test_entity',
  1445. 'bundle' => 'test_bundle',
  1446. 'default_value' => array(0 => array('value' => 99)),
  1447. );
  1448. field_create_field($field_no_access);
  1449. field_create_instance($instance_no_access);
  1450. $langcode = LANGUAGE_NONE;
  1451. // Test that the form structure includes full information for each delta
  1452. // apart from #access.
  1453. $entity_type = 'test_entity';
  1454. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  1455. $form = array();
  1456. $form_state = form_state_defaults();
  1457. field_attach_form($entity_type, $entity, $form, $form_state);
  1458. $this->assertEqual($form[$field_name_no_access][$langcode][0]['value']['#entity_type'], $entity_type, 'The correct entity type is set in the field structure.');
  1459. $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
  1460. // Display creation form.
  1461. $this->drupalGet('test-entity/add/test-bundle');
  1462. $this->assertNoFieldByName("{$field_name_no_access}[$langcode][0][value]", '', t('Widget is not displayed if field access is denied.'));
  1463. // Create entity.
  1464. $edit = array("{$field_name}[$langcode][0][value]" => 1);
  1465. $this->drupalPost(NULL, $edit, t('Save'));
  1466. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1467. $id = $match[1];
  1468. // Check that the default value was saved.
  1469. $entity = field_test_entity_test_load($id);
  1470. $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('Default value was saved for the field with no edit access.'));
  1471. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 1, t('Entered value vas saved for the field with edit access.'));
  1472. // Create a new revision.
  1473. $edit = array("{$field_name}[$langcode][0][value]" => 2, 'revision' => TRUE);
  1474. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1475. // Check that the new revision has the expected values.
  1476. $entity = field_test_entity_test_load($id);
  1477. $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('New revision has the expected value for the field with no edit access.'));
  1478. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));
  1479. // Check that the revision is also saved in the revisions table.
  1480. $entity = field_test_entity_test_load($id, $entity->ftvid);
  1481. $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('New revision has the expected value for the field with no edit access.'));
  1482. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));
  1483. }
  1484. /**
  1485. * Tests Field API form integration within a subform.
  1486. */
  1487. function testNestedFieldForm() {
  1488. // Add two instances on the 'test_bundle'
  1489. field_create_field($this->field_single);
  1490. field_create_field($this->field_unlimited);
  1491. $this->instance['field_name'] = 'field_single';
  1492. $this->instance['label'] = 'Single field';
  1493. field_create_instance($this->instance);
  1494. $this->instance['field_name'] = 'field_unlimited';
  1495. $this->instance['label'] = 'Unlimited field';
  1496. field_create_instance($this->instance);
  1497. // Create two entities.
  1498. $entity_1 = field_test_create_stub_entity(1, 1);
  1499. $entity_1->is_new = TRUE;
  1500. $entity_1->field_single[LANGUAGE_NONE][] = array('value' => 0);
  1501. $entity_1->field_unlimited[LANGUAGE_NONE][] = array('value' => 1);
  1502. field_test_entity_save($entity_1);
  1503. $entity_2 = field_test_create_stub_entity(2, 2);
  1504. $entity_2->is_new = TRUE;
  1505. $entity_2->field_single[LANGUAGE_NONE][] = array('value' => 10);
  1506. $entity_2->field_unlimited[LANGUAGE_NONE][] = array('value' => 11);
  1507. field_test_entity_save($entity_2);
  1508. // Display the 'combined form'.
  1509. $this->drupalGet('test-entity/nested/1/2');
  1510. $this->assertFieldByName('field_single[und][0][value]', 0, t('Entity 1: field_single value appears correctly is the form.'));
  1511. $this->assertFieldByName('field_unlimited[und][0][value]', 1, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
  1512. $this->assertFieldByName('entity_2[field_single][und][0][value]', 10, t('Entity 2: field_single value appears correctly is the form.'));
  1513. $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 11, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));
  1514. // Submit the form and check that the entities are updated accordingly.
  1515. $edit = array(
  1516. 'field_single[und][0][value]' => 1,
  1517. 'field_unlimited[und][0][value]' => 2,
  1518. 'field_unlimited[und][1][value]' => 3,
  1519. 'entity_2[field_single][und][0][value]' => 11,
  1520. 'entity_2[field_unlimited][und][0][value]' => 12,
  1521. 'entity_2[field_unlimited][und][1][value]' => 13,
  1522. );
  1523. $this->drupalPost(NULL, $edit, t('Save'));
  1524. field_cache_clear();
  1525. $entity_1 = field_test_create_stub_entity(1);
  1526. $entity_2 = field_test_create_stub_entity(2);
  1527. $this->assertFieldValues($entity_1, 'field_single', LANGUAGE_NONE, array(1));
  1528. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(2, 3));
  1529. $this->assertFieldValues($entity_2, 'field_single', LANGUAGE_NONE, array(11));
  1530. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(12, 13));
  1531. // Submit invalid values and check that errors are reported on the
  1532. // correct widgets.
  1533. $edit = array(
  1534. 'field_unlimited[und][1][value]' => -1,
  1535. );
  1536. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1537. $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 1: the field validation error was reported.'));
  1538. $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-und-1-value'));
  1539. $this->assertTrue($error_field, t('Entity 1: the error was flagged on the correct element.'));
  1540. $edit = array(
  1541. 'entity_2[field_unlimited][und][1][value]' => -1,
  1542. );
  1543. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1544. $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 2: the field validation error was reported.'));
  1545. $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-und-1-value'));
  1546. $this->assertTrue($error_field, t('Entity 2: the error was flagged on the correct element.'));
  1547. // Test that reordering works on both entities.
  1548. $edit = array(
  1549. 'field_unlimited[und][0][_weight]' => 0,
  1550. 'field_unlimited[und][1][_weight]' => -1,
  1551. 'entity_2[field_unlimited][und][0][_weight]' => 0,
  1552. 'entity_2[field_unlimited][und][1][_weight]' => -1,
  1553. );
  1554. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1555. field_cache_clear();
  1556. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
  1557. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 12));
  1558. // Test the 'add more' buttons. Only Ajax submission is tested, because
  1559. // the two 'add more' buttons present in the form have the same #value,
  1560. // which confuses drupalPost().
  1561. // 'Add more' button in the first entity:
  1562. $this->drupalGet('test-entity/nested/1/2');
  1563. $this->drupalPostAJAX(NULL, array(), 'field_unlimited_add_more');
  1564. $this->assertFieldByName('field_unlimited[und][0][value]', 3, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
  1565. $this->assertFieldByName('field_unlimited[und][1][value]', 2, t('Entity 1: field_unlimited value 1 appears correctly is the form.'));
  1566. $this->assertFieldByName('field_unlimited[und][2][value]', '', t('Entity 1: field_unlimited value 2 appears correctly is the form.'));
  1567. $this->assertFieldByName('field_unlimited[und][3][value]', '', t('Entity 1: an empty widget was added for field_unlimited value 3.'));
  1568. // 'Add more' button in the first entity (changing field values):
  1569. $edit = array(
  1570. 'entity_2[field_unlimited][und][0][value]' => 13,
  1571. 'entity_2[field_unlimited][und][1][value]' => 14,
  1572. 'entity_2[field_unlimited][und][2][value]' => 15,
  1573. );
  1574. $this->drupalPostAJAX(NULL, $edit, 'entity_2_field_unlimited_add_more');
  1575. $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 13, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));
  1576. $this->assertFieldByName('entity_2[field_unlimited][und][1][value]', 14, t('Entity 2: field_unlimited value 1 appears correctly is the form.'));
  1577. $this->assertFieldByName('entity_2[field_unlimited][und][2][value]', 15, t('Entity 2: field_unlimited value 2 appears correctly is the form.'));
  1578. $this->assertFieldByName('entity_2[field_unlimited][und][3][value]', '', t('Entity 2: an empty widget was added for field_unlimited value 3.'));
  1579. // Save the form and check values are saved correclty.
  1580. $this->drupalPost(NULL, array(), t('Save'));
  1581. field_cache_clear();
  1582. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
  1583. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 14, 15));
  1584. }
  1585. }
  1586. class FieldDisplayAPITestCase extends FieldTestCase {
  1587. public static function getInfo() {
  1588. return array(
  1589. 'name' => 'Field Display API tests',
  1590. 'description' => 'Test the display API.',
  1591. 'group' => 'Field API',
  1592. );
  1593. }
  1594. function setUp() {
  1595. parent::setUp('field_test');
  1596. // Create a field and instance.
  1597. $this->field_name = 'test_field';
  1598. $this->label = $this->randomName();
  1599. $this->cardinality = 4;
  1600. $this->field = array(
  1601. 'field_name' => $this->field_name,
  1602. 'type' => 'test_field',
  1603. 'cardinality' => $this->cardinality,
  1604. );
  1605. $this->instance = array(
  1606. 'field_name' => $this->field_name,
  1607. 'entity_type' => 'test_entity',
  1608. 'bundle' => 'test_bundle',
  1609. 'label' => $this->label,
  1610. 'display' => array(
  1611. 'default' => array(
  1612. 'type' => 'field_test_default',
  1613. 'settings' => array(
  1614. 'test_formatter_setting' => $this->randomName(),
  1615. ),
  1616. ),
  1617. 'teaser' => array(
  1618. 'type' => 'field_test_default',
  1619. 'settings' => array(
  1620. 'test_formatter_setting' => $this->randomName(),
  1621. ),
  1622. ),
  1623. ),
  1624. );
  1625. field_create_field($this->field);
  1626. field_create_instance($this->instance);
  1627. // Create an entity with values.
  1628. $this->values = $this->_generateTestFieldValues($this->cardinality);
  1629. $this->entity = field_test_create_stub_entity();
  1630. $this->is_new = TRUE;
  1631. $this->entity->{$this->field_name}[LANGUAGE_NONE] = $this->values;
  1632. field_test_entity_save($this->entity);
  1633. }
  1634. /**
  1635. * Test the field_view_field() function.
  1636. */
  1637. function testFieldViewField() {
  1638. // No display settings: check that default display settings are used.
  1639. $output = field_view_field('test_entity', $this->entity, $this->field_name);
  1640. $this->drupalSetContent(drupal_render($output));
  1641. $settings = field_info_formatter_settings('field_test_default');
  1642. $setting = $settings['test_formatter_setting'];
  1643. $this->assertText($this->label, t('Label was displayed.'));
  1644. foreach ($this->values as $delta => $value) {
  1645. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1646. }
  1647. // Check that explicit display settings are used.
  1648. $display = array(
  1649. 'label' => 'hidden',
  1650. 'type' => 'field_test_multiple',
  1651. 'settings' => array(
  1652. 'test_formatter_setting_multiple' => $this->randomName(),
  1653. 'alter' => TRUE,
  1654. ),
  1655. );
  1656. $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
  1657. $this->drupalSetContent(drupal_render($output));
  1658. $setting = $display['settings']['test_formatter_setting_multiple'];
  1659. $this->assertNoText($this->label, t('Label was not displayed.'));
  1660. $this->assertText('field_test_field_attach_view_alter', t('Alter fired, display passed.'));
  1661. $array = array();
  1662. foreach ($this->values as $delta => $value) {
  1663. $array[] = $delta . ':' . $value['value'];
  1664. }
  1665. $this->assertText($setting . '|' . implode('|', $array), t('Values were displayed with expected setting.'));
  1666. // Check the prepare_view steps are invoked.
  1667. $display = array(
  1668. 'label' => 'hidden',
  1669. 'type' => 'field_test_with_prepare_view',
  1670. 'settings' => array(
  1671. 'test_formatter_setting_additional' => $this->randomName(),
  1672. ),
  1673. );
  1674. $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
  1675. $view = drupal_render($output);
  1676. $this->drupalSetContent($view);
  1677. $setting = $display['settings']['test_formatter_setting_additional'];
  1678. $this->assertNoText($this->label, t('Label was not displayed.'));
  1679. $this->assertNoText('field_test_field_attach_view_alter', t('Alter not fired.'));
  1680. foreach ($this->values as $delta => $value) {
  1681. $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1682. }
  1683. // View mode: check that display settings specified in the instance are
  1684. // used.
  1685. $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
  1686. $this->drupalSetContent(drupal_render($output));
  1687. $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
  1688. $this->assertText($this->label, t('Label was displayed.'));
  1689. foreach ($this->values as $delta => $value) {
  1690. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1691. }
  1692. // Unknown view mode: check that display settings for 'default' view mode
  1693. // are used.
  1694. $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
  1695. $this->drupalSetContent(drupal_render($output));
  1696. $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
  1697. $this->assertText($this->label, t('Label was displayed.'));
  1698. foreach ($this->values as $delta => $value) {
  1699. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1700. }
  1701. }
  1702. /**
  1703. * Test the field_view_value() function.
  1704. */
  1705. function testFieldViewValue() {
  1706. // No display settings: check that default display settings are used.
  1707. $settings = field_info_formatter_settings('field_test_default');
  1708. $setting = $settings['test_formatter_setting'];
  1709. foreach ($this->values as $delta => $value) {
  1710. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1711. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
  1712. $this->drupalSetContent(drupal_render($output));
  1713. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1714. }
  1715. // Check that explicit display settings are used.
  1716. $display = array(
  1717. 'type' => 'field_test_multiple',
  1718. 'settings' => array(
  1719. 'test_formatter_setting_multiple' => $this->randomName(),
  1720. ),
  1721. );
  1722. $setting = $display['settings']['test_formatter_setting_multiple'];
  1723. $array = array();
  1724. foreach ($this->values as $delta => $value) {
  1725. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1726. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
  1727. $this->drupalSetContent(drupal_render($output));
  1728. $this->assertText($setting . '|0:' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1729. }
  1730. // Check that prepare_view steps are invoked.
  1731. $display = array(
  1732. 'type' => 'field_test_with_prepare_view',
  1733. 'settings' => array(
  1734. 'test_formatter_setting_additional' => $this->randomName(),
  1735. ),
  1736. );
  1737. $setting = $display['settings']['test_formatter_setting_additional'];
  1738. $array = array();
  1739. foreach ($this->values as $delta => $value) {
  1740. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1741. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
  1742. $this->drupalSetContent(drupal_render($output));
  1743. $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1744. }
  1745. // View mode: check that display settings specified in the instance are
  1746. // used.
  1747. $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
  1748. foreach ($this->values as $delta => $value) {
  1749. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1750. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
  1751. $this->drupalSetContent(drupal_render($output));
  1752. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1753. }
  1754. // Unknown view mode: check that display settings for 'default' view mode
  1755. // are used.
  1756. $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
  1757. foreach ($this->values as $delta => $value) {
  1758. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1759. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
  1760. $this->drupalSetContent(drupal_render($output));
  1761. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1762. }
  1763. }
  1764. }
  1765. class FieldCrudTestCase extends FieldTestCase {
  1766. public static function getInfo() {
  1767. return array(
  1768. 'name' => 'Field CRUD tests',
  1769. 'description' => 'Test field create, read, update, and delete.',
  1770. 'group' => 'Field API',
  1771. );
  1772. }
  1773. function setUp() {
  1774. // field_update_field() tests use number.module
  1775. parent::setUp('field_test', 'number');
  1776. }
  1777. // TODO : test creation with
  1778. // - a full fledged $field structure, check that all the values are there
  1779. // - a minimal $field structure, check all default values are set
  1780. // defer actual $field comparison to a helper function, used for the two cases above
  1781. /**
  1782. * Test the creation of a field.
  1783. */
  1784. function testCreateField() {
  1785. $field_definition = array(
  1786. 'field_name' => 'field_2',
  1787. 'type' => 'test_field',
  1788. );
  1789. field_test_memorize();
  1790. $field_definition = field_create_field($field_definition);
  1791. $mem = field_test_memorize();
  1792. $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');
  1793. // Read the raw record from the {field_config_instance} table.
  1794. $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
  1795. $record = $result->fetchAssoc();
  1796. $record['data'] = unserialize($record['data']);
  1797. // Ensure that basic properties are preserved.
  1798. $this->assertEqual($record['field_name'], $field_definition['field_name'], t('The field name is properly saved.'));
  1799. $this->assertEqual($record['type'], $field_definition['type'], t('The field type is properly saved.'));
  1800. // Ensure that cardinality defaults to 1.
  1801. $this->assertEqual($record['cardinality'], 1, t('Cardinality defaults to 1.'));
  1802. // Ensure that default settings are present.
  1803. $field_type = field_info_field_types($field_definition['type']);
  1804. $this->assertIdentical($record['data']['settings'], $field_type['settings'], t('Default field settings have been written.'));
  1805. // Ensure that default storage was set.
  1806. $this->assertEqual($record['storage_type'], variable_get('field_storage_default'), t('The field type is properly saved.'));
  1807. // Guarantee that the name is unique.
  1808. try {
  1809. field_create_field($field_definition);
  1810. $this->fail(t('Cannot create two fields with the same name.'));
  1811. }
  1812. catch (FieldException $e) {
  1813. $this->pass(t('Cannot create two fields with the same name.'));
  1814. }
  1815. // Check that field type is required.
  1816. try {
  1817. $field_definition = array(
  1818. 'field_name' => 'field_1',
  1819. );
  1820. field_create_field($field_definition);
  1821. $this->fail(t('Cannot create a field with no type.'));
  1822. }
  1823. catch (FieldException $e) {
  1824. $this->pass(t('Cannot create a field with no type.'));
  1825. }
  1826. // Check that field name is required.
  1827. try {
  1828. $field_definition = array(
  1829. 'type' => 'test_field'
  1830. );
  1831. field_create_field($field_definition);
  1832. $this->fail(t('Cannot create an unnamed field.'));
  1833. }
  1834. catch (FieldException $e) {
  1835. $this->pass(t('Cannot create an unnamed field.'));
  1836. }
  1837. // Check that field name must start with a letter or _.
  1838. try {
  1839. $field_definition = array(
  1840. 'field_name' => '2field_2',
  1841. 'type' => 'test_field',
  1842. );
  1843. field_create_field($field_definition);
  1844. $this->fail(t('Cannot create a field with a name starting with a digit.'));
  1845. }
  1846. catch (FieldException $e) {
  1847. $this->pass(t('Cannot create a field with a name starting with a digit.'));
  1848. }
  1849. // Check that field name must only contain lowercase alphanumeric or _.
  1850. try {
  1851. $field_definition = array(
  1852. 'field_name' => 'field#_3',
  1853. 'type' => 'test_field',
  1854. );
  1855. field_create_field($field_definition);
  1856. $this->fail(t('Cannot create a field with a name containing an illegal character.'));
  1857. }
  1858. catch (FieldException $e) {
  1859. $this->pass(t('Cannot create a field with a name containing an illegal character.'));
  1860. }
  1861. // Check that field name cannot be longer than 32 characters long.
  1862. try {
  1863. $field_definition = array(
  1864. 'field_name' => '_12345678901234567890123456789012',
  1865. 'type' => 'test_field',
  1866. );
  1867. field_create_field($field_definition);
  1868. $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
  1869. }
  1870. catch (FieldException $e) {
  1871. $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
  1872. }
  1873. // Check that field name can not be an entity key.
  1874. // "ftvid" is known as an entity key from the "test_entity" type.
  1875. try {
  1876. $field_definition = array(
  1877. 'type' => 'test_field',
  1878. 'field_name' => 'ftvid',
  1879. );
  1880. $field = field_create_field($field_definition);
  1881. $this->fail(t('Cannot create a field bearing the name of an entity key.'));
  1882. }
  1883. catch (FieldException $e) {
  1884. $this->pass(t('Cannot create a field bearing the name of an entity key.'));
  1885. }
  1886. }
  1887. /**
  1888. * Test failure to create a field.
  1889. */
  1890. function testCreateFieldFail() {
  1891. $field_name = 'duplicate';
  1892. $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
  1893. $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();
  1894. // The field does not appear in field_config.
  1895. $count = $query->execute()->fetchField();
  1896. $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
  1897. // Try to create the field.
  1898. try {
  1899. $field = field_create_field($field_definition);
  1900. $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
  1901. }
  1902. catch (Exception $e) {
  1903. $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
  1904. }
  1905. // The field does not appear in field_config.
  1906. $count = $query->execute()->fetchField();
  1907. $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
  1908. }
  1909. /**
  1910. * Test reading back a field definition.
  1911. */
  1912. function testReadField() {
  1913. $field_definition = array(
  1914. 'field_name' => 'field_1',
  1915. 'type' => 'test_field',
  1916. );
  1917. field_create_field($field_definition);
  1918. // Read the field back.
  1919. $field = field_read_field($field_definition['field_name']);
  1920. $this->assertTrue($field_definition < $field, t('The field was properly read.'));
  1921. }
  1922. /**
  1923. * Test creation of indexes on data column.
  1924. */
  1925. function testFieldIndexes() {
  1926. // Check that indexes specified by the field type are used by default.
  1927. $field_definition = array(
  1928. 'field_name' => 'field_1',
  1929. 'type' => 'test_field',
  1930. );
  1931. field_create_field($field_definition);
  1932. $field = field_read_field($field_definition['field_name']);
  1933. $expected_indexes = array('value' => array('value'));
  1934. $this->assertEqual($field['indexes'], $expected_indexes, t('Field type indexes saved by default'));
  1935. // Check that indexes specified by the field definition override the field
  1936. // type indexes.
  1937. $field_definition = array(
  1938. 'field_name' => 'field_2',
  1939. 'type' => 'test_field',
  1940. 'indexes' => array(
  1941. 'value' => array(),
  1942. ),
  1943. );
  1944. field_create_field($field_definition);
  1945. $field = field_read_field($field_definition['field_name']);
  1946. $expected_indexes = array('value' => array());
  1947. $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes override field type indexes'));
  1948. // Check that indexes specified by the field definition add to the field
  1949. // type indexes.
  1950. $field_definition = array(
  1951. 'field_name' => 'field_3',
  1952. 'type' => 'test_field',
  1953. 'indexes' => array(
  1954. 'value_2' => array('value'),
  1955. ),
  1956. );
  1957. field_create_field($field_definition);
  1958. $field = field_read_field($field_definition['field_name']);
  1959. $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
  1960. $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes are merged with field type indexes'));
  1961. }
  1962. /**
  1963. * Test the deletion of a field.
  1964. */
  1965. function testDeleteField() {
  1966. // TODO: Also test deletion of the data stored in the field ?
  1967. // Create two fields (so we can test that only one is deleted).
  1968. $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
  1969. field_create_field($this->field);
  1970. $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
  1971. field_create_field($this->another_field);
  1972. // Create instances for each.
  1973. $this->instance_definition = array(
  1974. 'field_name' => $this->field['field_name'],
  1975. 'entity_type' => 'test_entity',
  1976. 'bundle' => 'test_bundle',
  1977. 'widget' => array(
  1978. 'type' => 'test_field_widget',
  1979. ),
  1980. );
  1981. field_create_instance($this->instance_definition);
  1982. $this->another_instance_definition = $this->instance_definition;
  1983. $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
  1984. field_create_instance($this->another_instance_definition);
  1985. // Test that the first field is not deleted, and then delete it.
  1986. $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
  1987. $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field is not marked for deletion.'));
  1988. field_delete_field($this->field['field_name']);
  1989. // Make sure that the field is marked as deleted when it is specifically
  1990. // loaded.
  1991. $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
  1992. $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion.'));
  1993. // Make sure that this field's instance is marked as deleted when it is
  1994. // specifically loaded.
  1995. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  1996. $this->assertTrue(!empty($instance['deleted']), t('An instance for a deleted field is marked for deletion.'));
  1997. // Try to load the field normally and make sure it does not show up.
  1998. $field = field_read_field($this->field['field_name']);
  1999. $this->assertTrue(empty($field), t('A deleted field is not loaded by default.'));
  2000. // Try to load the instance normally and make sure it does not show up.
  2001. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2002. $this->assertTrue(empty($instance), t('An instance for a deleted field is not loaded by default.'));
  2003. // Make sure the other field (and its field instance) are not deleted.
  2004. $another_field = field_read_field($this->another_field['field_name']);
  2005. $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), t('A non-deleted field is not marked for deletion.'));
  2006. $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
  2007. $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('An instance of a non-deleted field is not marked for deletion.'));
  2008. // Try to create a new field the same name as a deleted field and
  2009. // write data into it.
  2010. field_create_field($this->field);
  2011. field_create_instance($this->instance_definition);
  2012. $field = field_read_field($this->field['field_name']);
  2013. $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field with a previously used name is created.'));
  2014. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2015. $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new instance for a previously used field name is created.'));
  2016. // Save an entity with data for the field
  2017. $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
  2018. $langcode = LANGUAGE_NONE;
  2019. $values[0]['value'] = mt_rand(1, 127);
  2020. $entity->{$field['field_name']}[$langcode] = $values;
  2021. $entity_type = 'test_entity';
  2022. field_attach_insert('test_entity', $entity);
  2023. // Verify the field is present on load
  2024. $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
  2025. field_attach_load($entity_type, array(0 => $entity));
  2026. $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
  2027. foreach ($values as $delta => $value) {
  2028. $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
  2029. }
  2030. }
  2031. function testUpdateNonExistentField() {
  2032. $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
  2033. try {
  2034. field_update_field($test_field);
  2035. $this->fail(t('Cannot update a field that does not exist.'));
  2036. }
  2037. catch (FieldException $e) {
  2038. $this->pass(t('Cannot update a field that does not exist.'));
  2039. }
  2040. }
  2041. function testUpdateFieldType() {
  2042. $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
  2043. $field = field_create_field($field);
  2044. $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
  2045. try {
  2046. field_update_field($test_field);
  2047. $this->fail(t('Cannot update a field to a different type.'));
  2048. }
  2049. catch (FieldException $e) {
  2050. $this->pass(t('Cannot update a field to a different type.'));
  2051. }
  2052. }
  2053. /**
  2054. * Test updating a field.
  2055. */
  2056. function testUpdateField() {
  2057. // Create a field with a defined cardinality, so that we can ensure it's
  2058. // respected. Since cardinality enforcement is consistent across database
  2059. // systems, it makes a good test case.
  2060. $cardinality = 4;
  2061. $field_definition = array(
  2062. 'field_name' => 'field_update',
  2063. 'type' => 'test_field',
  2064. 'cardinality' => $cardinality,
  2065. );
  2066. $field_definition = field_create_field($field_definition);
  2067. $instance = array(
  2068. 'field_name' => 'field_update',
  2069. 'entity_type' => 'test_entity',
  2070. 'bundle' => 'test_bundle',
  2071. );
  2072. $instance = field_create_instance($instance);
  2073. do {
  2074. // We need a unique ID for our entity. $cardinality will do.
  2075. $id = $cardinality;
  2076. $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
  2077. // Fill in the entity with more values than $cardinality.
  2078. for ($i = 0; $i < 20; $i++) {
  2079. $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
  2080. }
  2081. // Save the entity.
  2082. field_attach_insert('test_entity', $entity);
  2083. // Load back and assert there are $cardinality number of values.
  2084. $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
  2085. field_attach_load('test_entity', array($id => $entity));
  2086. $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
  2087. // Now check the values themselves.
  2088. for ($delta = 0; $delta < $cardinality; $delta++) {
  2089. $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
  2090. }
  2091. // Increase $cardinality and set the field cardinality to the new value.
  2092. $field_definition['cardinality'] = ++$cardinality;
  2093. field_update_field($field_definition);
  2094. } while ($cardinality < 6);
  2095. }
  2096. /**
  2097. * Test field type modules forbidding an update.
  2098. */
  2099. function testUpdateFieldForbid() {
  2100. $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
  2101. $field = field_create_field($field);
  2102. $field['settings']['changeable']++;
  2103. try {
  2104. field_update_field($field);
  2105. $this->pass(t("A changeable setting can be updated."));
  2106. }
  2107. catch (FieldException $e) {
  2108. $this->fail(t("An unchangeable setting cannot be updated."));
  2109. }
  2110. $field['settings']['unchangeable']++;
  2111. try {
  2112. field_update_field($field);
  2113. $this->fail(t("An unchangeable setting can be updated."));
  2114. }
  2115. catch (FieldException $e) {
  2116. $this->pass(t("An unchangeable setting cannot be updated."));
  2117. }
  2118. }
  2119. /**
  2120. * Test that fields are properly marked active or inactive.
  2121. */
  2122. function testActive() {
  2123. $field_definition = array(
  2124. 'field_name' => 'field_1',
  2125. 'type' => 'test_field',
  2126. // For this test, we need a storage backend provided by a different
  2127. // module than field_test.module.
  2128. 'storage' => array(
  2129. 'type' => 'field_sql_storage',
  2130. ),
  2131. );
  2132. field_create_field($field_definition);
  2133. // Test disabling and enabling:
  2134. // - the field type module,
  2135. // - the storage module,
  2136. // - both.
  2137. $this->_testActiveHelper($field_definition, array('field_test'));
  2138. $this->_testActiveHelper($field_definition, array('field_sql_storage'));
  2139. $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
  2140. }
  2141. /**
  2142. * Helper function for testActive().
  2143. *
  2144. * Test dependency between a field and a set of modules.
  2145. *
  2146. * @param $field_definition
  2147. * A field definition.
  2148. * @param $modules
  2149. * An aray of module names. The field will be tested to be inactive as long
  2150. * as any of those modules is disabled.
  2151. */
  2152. function _testActiveHelper($field_definition, $modules) {
  2153. $field_name = $field_definition['field_name'];
  2154. // Read the field.
  2155. $field = field_read_field($field_name);
  2156. $this->assertTrue($field_definition <= $field, t('The field was properly read.'));
  2157. module_disable($modules, FALSE);
  2158. $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
  2159. $this->assertTrue(isset($fields[$field_name]) && $field_definition < $field, t('The field is properly read when explicitly fetching inactive fields.'));
  2160. // Re-enable modules one by one, and check that the field is still inactive
  2161. // while some modules remain disabled.
  2162. while ($modules) {
  2163. $field = field_read_field($field_name);
  2164. $this->assertTrue(empty($field), t('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));
  2165. $module = array_shift($modules);
  2166. module_enable(array($module), FALSE);
  2167. }
  2168. // Check that the field is active again after all modules have been
  2169. // enabled.
  2170. $field = field_read_field($field_name);
  2171. $this->assertTrue($field_definition <= $field, t('The field was was marked active.'));
  2172. }
  2173. }
  2174. class FieldInstanceCrudTestCase extends FieldTestCase {
  2175. protected $field;
  2176. public static function getInfo() {
  2177. return array(
  2178. 'name' => 'Field instance CRUD tests',
  2179. 'description' => 'Create field entities by attaching fields to entities.',
  2180. 'group' => 'Field API',
  2181. );
  2182. }
  2183. function setUp() {
  2184. parent::setUp('field_test');
  2185. $this->field = array(
  2186. 'field_name' => drupal_strtolower($this->randomName()),
  2187. 'type' => 'test_field',
  2188. );
  2189. field_create_field($this->field);
  2190. $this->instance_definition = array(
  2191. 'field_name' => $this->field['field_name'],
  2192. 'entity_type' => 'test_entity',
  2193. 'bundle' => 'test_bundle',
  2194. );
  2195. }
  2196. // TODO : test creation with
  2197. // - a full fledged $instance structure, check that all the values are there
  2198. // - a minimal $instance structure, check all default values are set
  2199. // defer actual $instance comparison to a helper function, used for the two cases above,
  2200. // and for testUpdateFieldInstance
  2201. /**
  2202. * Test the creation of a field instance.
  2203. */
  2204. function testCreateFieldInstance() {
  2205. field_create_instance($this->instance_definition);
  2206. // Read the raw record from the {field_config_instance} table.
  2207. $result = db_query('SELECT * FROM {field_config_instance} WHERE field_name = :field_name AND bundle = :bundle', array(':field_name' => $this->instance_definition['field_name'], ':bundle' => $this->instance_definition['bundle']));
  2208. $record = $result->fetchAssoc();
  2209. $record['data'] = unserialize($record['data']);
  2210. $field_type = field_info_field_types($this->field['type']);
  2211. $widget_type = field_info_widget_types($field_type['default_widget']);
  2212. $formatter_type = field_info_formatter_types($field_type['default_formatter']);
  2213. // Check that default values are set.
  2214. $this->assertIdentical($record['data']['required'], FALSE, t('Required defaults to false.'));
  2215. $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], t('Label defaults to field name.'));
  2216. $this->assertIdentical($record['data']['description'], '', t('Description defaults to empty string.'));
  2217. $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], t('Default widget has been written.'));
  2218. $this->assertTrue(isset($record['data']['display']['default']), t('Display for "full" view_mode has been written.'));
  2219. $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], t('Default formatter for "full" view_mode has been written.'));
  2220. // Check that default settings are set.
  2221. $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , t('Default instance settings have been written.'));
  2222. $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , t('Default widget settings have been written.'));
  2223. $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], t('Default formatter settings for "full" view_mode have been written.'));
  2224. // Guarantee that the field/bundle combination is unique.
  2225. try {
  2226. field_create_instance($this->instance_definition);
  2227. $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
  2228. }
  2229. catch (FieldException $e) {
  2230. $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
  2231. }
  2232. // Check that the specified field exists.
  2233. try {
  2234. $this->instance_definition['field_name'] = $this->randomName();
  2235. field_create_instance($this->instance_definition);
  2236. $this->fail(t('Cannot create an instance of a non-existing field.'));
  2237. }
  2238. catch (FieldException $e) {
  2239. $this->pass(t('Cannot create an instance of a non-existing field.'));
  2240. }
  2241. // Create a field restricted to a specific entity type.
  2242. $field_restricted = array(
  2243. 'field_name' => drupal_strtolower($this->randomName()),
  2244. 'type' => 'test_field',
  2245. 'entity_types' => array('test_cacheable_entity'),
  2246. );
  2247. field_create_field($field_restricted);
  2248. // Check that an instance can be added to an entity type allowed
  2249. // by the field.
  2250. try {
  2251. $instance = $this->instance_definition;
  2252. $instance['field_name'] = $field_restricted['field_name'];
  2253. $instance['entity_type'] = 'test_cacheable_entity';
  2254. field_create_instance($instance);
  2255. $this->pass(t('Can create an instance on an entity type allowed by the field.'));
  2256. }
  2257. catch (FieldException $e) {
  2258. $this->fail(t('Can create an instance on an entity type allowed by the field.'));
  2259. }
  2260. // Check that an instance cannot be added to an entity type
  2261. // forbidden by the field.
  2262. try {
  2263. $instance = $this->instance_definition;
  2264. $instance['field_name'] = $field_restricted['field_name'];
  2265. field_create_instance($instance);
  2266. $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
  2267. }
  2268. catch (FieldException $e) {
  2269. $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
  2270. }
  2271. // TODO: test other failures.
  2272. }
  2273. /**
  2274. * Test reading back an instance definition.
  2275. */
  2276. function testReadFieldInstance() {
  2277. field_create_instance($this->instance_definition);
  2278. // Read the instance back.
  2279. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2280. $this->assertTrue($this->instance_definition < $instance, t('The field was properly read.'));
  2281. }
  2282. /**
  2283. * Test the update of a field instance.
  2284. */
  2285. function testUpdateFieldInstance() {
  2286. field_create_instance($this->instance_definition);
  2287. $field_type = field_info_field_types($this->field['type']);
  2288. // Check that basic changes are saved.
  2289. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2290. $instance['required'] = !$instance['required'];
  2291. $instance['label'] = $this->randomName();
  2292. $instance['description'] = $this->randomName();
  2293. $instance['settings']['test_instance_setting'] = $this->randomName();
  2294. $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
  2295. $instance['widget']['weight']++;
  2296. $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
  2297. $instance['display']['default']['weight']++;
  2298. field_update_instance($instance);
  2299. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2300. $this->assertEqual($instance['required'], $instance_new['required'], t('"required" change is saved'));
  2301. $this->assertEqual($instance['label'], $instance_new['label'], t('"label" change is saved'));
  2302. $this->assertEqual($instance['description'], $instance_new['description'], t('"description" change is saved'));
  2303. $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], t('Widget setting change is saved'));
  2304. $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], t('Widget weight change is saved'));
  2305. $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], t('Formatter setting change is saved'));
  2306. $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], t('Widget weight change is saved'));
  2307. // Check that changing widget and formatter types updates the default settings.
  2308. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2309. $instance['widget']['type'] = 'test_field_widget_multiple';
  2310. $instance['display']['default']['type'] = 'field_test_multiple';
  2311. field_update_instance($instance);
  2312. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2313. $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , t('Widget type change is saved.'));
  2314. $settings = field_info_widget_settings($instance_new['widget']['type']);
  2315. $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , t('Widget type change updates default settings.'));
  2316. $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , t('Formatter type change is saved.'));
  2317. $info = field_info_formatter_types($instance_new['display']['default']['type']);
  2318. $settings = $info['settings'];
  2319. $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , t('Changing formatter type updates default settings.'));
  2320. // Check that adding a new view mode is saved and gets default settings.
  2321. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2322. $instance['display']['teaser'] = array();
  2323. field_update_instance($instance);
  2324. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2325. $this->assertTrue(isset($instance_new['display']['teaser']), t('Display for the new view_mode has been written.'));
  2326. $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], t('Default formatter for the new view_mode has been written.'));
  2327. $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
  2328. $settings = $info['settings'];
  2329. $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , t('Default formatter settings for the new view_mode have been written.'));
  2330. // TODO: test failures.
  2331. }
  2332. /**
  2333. * Test the deletion of a field instance.
  2334. */
  2335. function testDeleteFieldInstance() {
  2336. // TODO: Test deletion of the data stored in the field also.
  2337. // Need to check that data for a 'deleted' field / instance doesn't get loaded
  2338. // Need to check data marked deleted is cleaned on cron (not implemented yet...)
  2339. // Create two instances for the same field so we can test that only one
  2340. // is deleted.
  2341. field_create_instance($this->instance_definition);
  2342. $this->another_instance_definition = $this->instance_definition;
  2343. $this->another_instance_definition['bundle'] .= '_another_bundle';
  2344. $instance = field_create_instance($this->another_instance_definition);
  2345. // Test that the first instance is not deleted, and then delete it.
  2346. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  2347. $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new field instance is not marked for deletion.'));
  2348. field_delete_instance($instance);
  2349. // Make sure the instance is marked as deleted when the instance is
  2350. // specifically loaded.
  2351. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  2352. $this->assertTrue(!empty($instance['deleted']), t('A deleted field instance is marked for deletion.'));
  2353. // Try to load the instance normally and make sure it does not show up.
  2354. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2355. $this->assertTrue(empty($instance), t('A deleted field instance is not loaded by default.'));
  2356. // Make sure the other field instance is not deleted.
  2357. $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
  2358. $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('A non-deleted field instance is not marked for deletion.'));
  2359. // Make sure the field is deleted when its last instance is deleted.
  2360. field_delete_instance($another_instance);
  2361. $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
  2362. $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion after all its instances have been marked for deletion.'));
  2363. }
  2364. }
  2365. /**
  2366. * Unit test class for the multilanguage fields logic.
  2367. *
  2368. * The following tests will check the multilanguage logic of _field_invoke() and
  2369. * that only the correct values are returned by field_available_languages().
  2370. */
  2371. class FieldTranslationsTestCase extends FieldTestCase {
  2372. public static function getInfo() {
  2373. return array(
  2374. 'name' => 'Field translations tests',
  2375. 'description' => 'Test multilanguage fields logic.',
  2376. 'group' => 'Field API',
  2377. );
  2378. }
  2379. function setUp() {
  2380. parent::setUp('locale', 'field_test');
  2381. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  2382. $this->entity_type = 'test_entity';
  2383. $field = array(
  2384. 'field_name' => $this->field_name,
  2385. 'type' => 'test_field',
  2386. 'cardinality' => 4,
  2387. 'translatable' => TRUE,
  2388. );
  2389. field_create_field($field);
  2390. $this->field = field_read_field($this->field_name);
  2391. $instance = array(
  2392. 'field_name' => $this->field_name,
  2393. 'entity_type' => $this->entity_type,
  2394. 'bundle' => 'test_bundle',
  2395. );
  2396. field_create_instance($instance);
  2397. $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');
  2398. require_once DRUPAL_ROOT . '/includes/locale.inc';
  2399. for ($i = 0; $i < 3; ++$i) {
  2400. locale_add_language('l' . $i, $this->randomString(), $this->randomString());
  2401. }
  2402. }
  2403. /**
  2404. * Ensures that only valid values are returned by field_available_languages().
  2405. */
  2406. function testFieldAvailableLanguages() {
  2407. // Test 'translatable' fieldable info.
  2408. field_test_entity_info_translatable('test_entity', FALSE);
  2409. $field = $this->field;
  2410. $field['field_name'] .= '_untranslatable';
  2411. // Enable field translations for the entity.
  2412. field_test_entity_info_translatable('test_entity', TRUE);
  2413. // Test hook_field_languages() invocation on a translatable field.
  2414. variable_set('field_test_field_available_languages_alter', TRUE);
  2415. $enabled_languages = field_content_languages();
  2416. $available_languages = field_available_languages($this->entity_type, $this->field);
  2417. foreach ($available_languages as $delta => $langcode) {
  2418. if ($langcode != 'xx' && $langcode != 'en') {
  2419. $this->assertTrue(in_array($langcode, $enabled_languages), t('%language is an enabled language.', array('%language' => $langcode)));
  2420. }
  2421. }
  2422. $this->assertTrue(in_array('xx', $available_languages), t('%language was made available.', array('%language' => 'xx')));
  2423. $this->assertFalse(in_array('en', $available_languages), t('%language was made unavailable.', array('%language' => 'en')));
  2424. // Test field_available_languages() behavior for untranslatable fields.
  2425. $this->field['translatable'] = FALSE;
  2426. field_update_field($this->field);
  2427. $available_languages = field_available_languages($this->entity_type, $this->field);
  2428. $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, t('For untranslatable fields only LANGUAGE_NONE is available.'));
  2429. }
  2430. /**
  2431. * Test the multilanguage logic of _field_invoke().
  2432. */
  2433. function testFieldInvoke() {
  2434. // Enable field translations for the entity.
  2435. field_test_entity_info_translatable('test_entity', TRUE);
  2436. $entity_type = 'test_entity';
  2437. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  2438. // Populate some extra languages to check if _field_invoke() correctly uses
  2439. // the result of field_available_languages().
  2440. $values = array();
  2441. $extra_languages = mt_rand(1, 4);
  2442. $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
  2443. for ($i = 0; $i < $extra_languages; ++$i) {
  2444. $languages[] = $this->randomName(2);
  2445. }
  2446. // For each given language provide some random values.
  2447. foreach ($languages as $langcode) {
  2448. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  2449. $values[$langcode][$delta]['value'] = mt_rand(1, 127);
  2450. }
  2451. }
  2452. $entity->{$this->field_name} = $values;
  2453. $results = _field_invoke('test_op', $entity_type, $entity);
  2454. foreach ($results as $langcode => $result) {
  2455. $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
  2456. // Check whether the parameters passed to _field_invoke() were correctly
  2457. // forwarded to the callback function.
  2458. $this->assertEqual($hash, $result, t('The result for %language is correctly stored.', array('%language' => $langcode)));
  2459. }
  2460. $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed.'));
  2461. }
  2462. /**
  2463. * Test the multilanguage logic of _field_invoke_multiple().
  2464. */
  2465. function testFieldInvokeMultiple() {
  2466. // Enable field translations for the entity.
  2467. field_test_entity_info_translatable('test_entity', TRUE);
  2468. $values = array();
  2469. $options = array();
  2470. $entities = array();
  2471. $entity_type = 'test_entity';
  2472. $entity_count = 5;
  2473. $available_languages = field_available_languages($this->entity_type, $this->field);
  2474. for ($id = 1; $id <= $entity_count; ++$id) {
  2475. $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
  2476. $languages = $available_languages;
  2477. // Populate some extra languages to check whether _field_invoke()
  2478. // correctly uses the result of field_available_languages().
  2479. $extra_languages = mt_rand(1, 4);
  2480. for ($i = 0; $i < $extra_languages; ++$i) {
  2481. $languages[] = $this->randomName(2);
  2482. }
  2483. // For each given language provide some random values.
  2484. $language_count = count($languages);
  2485. for ($i = 0; $i < $language_count; ++$i) {
  2486. $langcode = $languages[$i];
  2487. // Avoid to populate at least one field translation to check that
  2488. // per-entity language suggestions work even when available field values
  2489. // are different for each language.
  2490. if ($i !== $id) {
  2491. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  2492. $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
  2493. }
  2494. }
  2495. // Ensure that a language for which there is no field translation is
  2496. // used as display language to prepare per-entity language suggestions.
  2497. elseif (!isset($display_language)) {
  2498. $display_language = $langcode;
  2499. }
  2500. }
  2501. $entity->{$this->field_name} = $values[$id];
  2502. $entities[$id] = $entity;
  2503. // Store per-entity language suggestions.
  2504. $options['language'][$id] = field_language($entity_type, $entity, NULL, $display_language);
  2505. }
  2506. $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
  2507. foreach ($grouped_results as $id => $results) {
  2508. foreach ($results as $langcode => $result) {
  2509. if (isset($values[$id][$langcode])) {
  2510. $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
  2511. // Check whether the parameters passed to _field_invoke_multiple()
  2512. // were correctly forwarded to the callback function.
  2513. $this->assertEqual($hash, $result, t('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
  2514. }
  2515. }
  2516. $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed for entity %id.', array('%id' => $id)));
  2517. }
  2518. $null = NULL;
  2519. $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities, $null, $null, $options);
  2520. foreach ($grouped_results as $id => $results) {
  2521. foreach ($results as $langcode => $result) {
  2522. $this->assertTrue(isset($options['language'][$id]), t('The result language %language for entity %id was correctly suggested (display language: %display_language).', array('%id' => $id, '%language' => $langcode, '%display_language' => $display_language)));
  2523. }
  2524. }
  2525. }
  2526. /**
  2527. * Test translatable fields storage/retrieval.
  2528. */
  2529. function testTranslatableFieldSaveLoad() {
  2530. // Enable field translations for nodes.
  2531. field_test_entity_info_translatable('node', TRUE);
  2532. $entity_info = entity_get_info('node');
  2533. $this->assertTrue(count($entity_info['translation']), t('Nodes are translatable.'));
  2534. // Prepare the field translations.
  2535. field_test_entity_info_translatable('test_entity', TRUE);
  2536. $eid = $evid = 1;
  2537. $entity_type = 'test_entity';
  2538. $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
  2539. $field_translations = array();
  2540. $available_languages = field_available_languages($entity_type, $this->field);
  2541. $this->assertTrue(count($available_languages) > 1, t('Field is translatable.'));
  2542. foreach ($available_languages as $langcode) {
  2543. $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
  2544. }
  2545. // Save and reload the field translations.
  2546. $entity->{$this->field_name} = $field_translations;
  2547. field_attach_insert($entity_type, $entity);
  2548. unset($entity->{$this->field_name});
  2549. field_attach_load($entity_type, array($eid => $entity));
  2550. // Check if the correct values were saved/loaded.
  2551. foreach ($field_translations as $langcode => $items) {
  2552. $result = TRUE;
  2553. foreach ($items as $delta => $item) {
  2554. $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
  2555. }
  2556. $this->assertTrue($result, t('%language translation correctly handled.', array('%language' => $langcode)));
  2557. }
  2558. }
  2559. /**
  2560. * Tests display language logic for translatable fields.
  2561. */
  2562. function testFieldDisplayLanguage() {
  2563. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  2564. $entity_type = 'test_entity';
  2565. // We need an additional field here to properly test display language
  2566. // suggestions.
  2567. $field = array(
  2568. 'field_name' => $field_name,
  2569. 'type' => 'test_field',
  2570. 'cardinality' => 2,
  2571. 'translatable' => TRUE,
  2572. );
  2573. field_create_field($field);
  2574. $instance = array(
  2575. 'field_name' => $field['field_name'],
  2576. 'entity_type' => $entity_type,
  2577. 'bundle' => 'test_bundle',
  2578. );
  2579. field_create_instance($instance);
  2580. $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
  2581. $instances = field_info_instances($entity_type, $this->instance['bundle']);
  2582. $enabled_languages = field_content_languages();
  2583. $languages = array();
  2584. // Generate field translations for languages different from the first
  2585. // enabled.
  2586. foreach ($instances as $instance) {
  2587. $field_name = $instance['field_name'];
  2588. $field = field_info_field($field_name);
  2589. do {
  2590. // Index 0 is reserved for the requested language, this way we ensure
  2591. // that no field is actually populated with it.
  2592. $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
  2593. }
  2594. while (isset($languages[$langcode]));
  2595. $languages[$langcode] = TRUE;
  2596. $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
  2597. }
  2598. // Test multiple-fields display languages for untranslatable entities.
  2599. field_test_entity_info_translatable($entity_type, FALSE);
  2600. drupal_static_reset('field_language');
  2601. $requested_language = $enabled_languages[0];
  2602. $display_language = field_language($entity_type, $entity, NULL, $requested_language);
  2603. foreach ($instances as $instance) {
  2604. $field_name = $instance['field_name'];
  2605. $this->assertTrue($display_language[$field_name] == LANGUAGE_NONE, t('The display language for field %field_name is %language.', array('%field_name' => $field_name, '%language' => LANGUAGE_NONE)));
  2606. }
  2607. // Test multiple-fields display languages for translatable entities.
  2608. field_test_entity_info_translatable($entity_type, TRUE);
  2609. drupal_static_reset('field_language');
  2610. $display_language = field_language($entity_type, $entity, NULL, $requested_language);
  2611. foreach ($instances as $instance) {
  2612. $field_name = $instance['field_name'];
  2613. $langcode = $display_language[$field_name];
  2614. // As the requested language was not assinged to any field, if the
  2615. // returned language is defined for the current field, core fallback rules
  2616. // were successfully applied.
  2617. $this->assertTrue(isset($entity->{$field_name}[$langcode]) && $langcode != $requested_language, t('The display language for the field %field_name is %language.', array('%field_name' => $field_name, '%language' => $langcode)));
  2618. }
  2619. // Test single-field display language.
  2620. drupal_static_reset('field_language');
  2621. $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
  2622. $this->assertTrue(isset($entity->{$this->field_name}[$langcode]) && $langcode != $requested_language, t('The display language for the (single) field %field_name is %language.', array('%field_name' => $field_name, '%language' => $langcode)));
  2623. // Test field_language() basic behavior without language fallback.
  2624. variable_set('field_test_language_fallback', FALSE);
  2625. $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
  2626. drupal_static_reset('field_language');
  2627. $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
  2628. $this->assertEqual($display_language, $requested_language, t('Display language behave correctly when language fallback is disabled'));
  2629. }
  2630. /**
  2631. * Tests field translations when creating a new revision.
  2632. */
  2633. function testFieldFormTranslationRevisions() {
  2634. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
  2635. $this->drupalLogin($web_user);
  2636. // Prepare the field translations.
  2637. field_test_entity_info_translatable($this->entity_type, TRUE);
  2638. $eid = 1;
  2639. $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
  2640. $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
  2641. unset($available_languages[LANGUAGE_NONE]);
  2642. $field_name = $this->field['field_name'];
  2643. // Store the field translations.
  2644. $entity->is_new = TRUE;
  2645. foreach ($available_languages as $langcode => $value) {
  2646. $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
  2647. }
  2648. field_test_entity_save($entity);
  2649. // Create a new revision.
  2650. $langcode = field_valid_language(NULL);
  2651. $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
  2652. $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));
  2653. // Check translation revisions.
  2654. $this->checkTranslationRevisions($eid, $eid, $available_languages);
  2655. $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
  2656. }
  2657. /**
  2658. * Check if the field translation attached to the entity revision identified
  2659. * by the passed arguments were correctly stored.
  2660. */
  2661. private function checkTranslationRevisions($eid, $evid, $available_languages) {
  2662. $field_name = $this->field['field_name'];
  2663. $entity = field_test_entity_test_load($eid, $evid);
  2664. foreach ($available_languages as $langcode => $value) {
  2665. $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
  2666. $this->assertTrue($passed, t('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
  2667. }
  2668. }
  2669. }
  2670. /**
  2671. * Unit test class for field bulk delete and batch purge functionality.
  2672. */
  2673. class FieldBulkDeleteTestCase extends FieldTestCase {
  2674. protected $field;
  2675. public static function getInfo() {
  2676. return array(
  2677. 'name' => 'Field bulk delete tests',
  2678. 'description' => 'Bulk delete fields and instances, and clean up afterwards.',
  2679. 'group' => 'Field API',
  2680. );
  2681. }
  2682. /**
  2683. * Convenience function for Field API tests.
  2684. *
  2685. * Given an array of potentially fully-populated entities and an
  2686. * optional field name, generate an array of stub entities of the
  2687. * same fieldable type which contains the data for the field name
  2688. * (if given).
  2689. *
  2690. * @param $entity_type
  2691. * The entity type of $entities.
  2692. * @param $entities
  2693. * An array of entities of type $entity_type.
  2694. * @param $field_name
  2695. * Optional; a field name whose data should be copied from
  2696. * $entities into the returned stub entities.
  2697. * @return
  2698. * An array of stub entities corresponding to $entities.
  2699. */
  2700. function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
  2701. $stubs = array();
  2702. foreach ($entities as $id => $entity) {
  2703. $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
  2704. if (isset($field_name)) {
  2705. $stub->{$field_name} = $entity->{$field_name};
  2706. }
  2707. $stubs[$id] = $stub;
  2708. }
  2709. return $stubs;
  2710. }
  2711. /**
  2712. * Tests that the expected hooks have been invoked on the expected entities.
  2713. *
  2714. * @param $expected_hooks
  2715. * An array keyed by hook name, with one entry per expected invocation.
  2716. * Each entry is the value of the "$entity" parameter the hook is expected
  2717. * to have been passed.
  2718. * @param $actual_hooks
  2719. * The array of actual hook invocations recorded by field_test_memorize().
  2720. */
  2721. function checkHooksInvocations($expected_hooks, $actual_hooks) {
  2722. foreach ($expected_hooks as $hook => $invocations) {
  2723. $actual_invocations = $actual_hooks[$hook];
  2724. // Check that the number of invocations is correct.
  2725. $this->assertEqual(count($actual_invocations), count($invocations), "$hook() was called the expected number of times.");
  2726. // Check that the hook was called for each expected argument.
  2727. foreach ($invocations as $argument) {
  2728. $found = FALSE;
  2729. foreach ($actual_invocations as $actual_arguments) {
  2730. if ($actual_arguments[1] == $argument) {
  2731. $found = TRUE;
  2732. break;
  2733. }
  2734. }
  2735. $this->assertTrue($found, "$hook() was called on expected argument");
  2736. }
  2737. }
  2738. }
  2739. function setUp() {
  2740. parent::setUp('field_test');
  2741. $this->fields = array();
  2742. $this->instances = array();
  2743. $this->entities = array();
  2744. $this->entities_by_bundles = array();
  2745. // Create two bundles.
  2746. $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
  2747. foreach ($this->bundles as $name => $desc) {
  2748. field_test_create_bundle($name, $desc);
  2749. }
  2750. // Create two fields.
  2751. $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
  2752. $this->fields[] = field_create_field($field);
  2753. $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
  2754. $this->fields[] = field_create_field($field);
  2755. // For each bundle, create an instance of each field, and 10
  2756. // entities with values for each field.
  2757. $id = 0;
  2758. $this->entity_type = 'test_entity';
  2759. foreach ($this->bundles as $bundle) {
  2760. foreach ($this->fields as $field) {
  2761. $instance = array(
  2762. 'field_name' => $field['field_name'],
  2763. 'entity_type' => $this->entity_type,
  2764. 'bundle' => $bundle,
  2765. 'widget' => array(
  2766. 'type' => 'test_field_widget',
  2767. )
  2768. );
  2769. $this->instances[] = field_create_instance($instance);
  2770. }
  2771. for ($i = 0; $i < 10; $i++) {
  2772. $entity = field_test_create_stub_entity($id, $id, $bundle);
  2773. foreach ($this->fields as $field) {
  2774. $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
  2775. }
  2776. $this->entities[$id] = $entity;
  2777. // Also keep track of the entities per bundle.
  2778. $this->entities_by_bundles[$bundle][$id] = $entity;
  2779. field_attach_insert($this->entity_type, $entity);
  2780. $id++;
  2781. }
  2782. }
  2783. }
  2784. /**
  2785. * Verify that deleting an instance leaves the field data items in
  2786. * the database and that the appropriate Field API functions can
  2787. * operate on the deleted data and instance.
  2788. *
  2789. * This tests how EntityFieldQuery interacts with
  2790. * field_delete_instance() and could be moved to FieldCrudTestCase,
  2791. * but depends on this class's setUp().
  2792. */
  2793. function testDeleteFieldInstance() {
  2794. $bundle = reset($this->bundles);
  2795. $field = reset($this->fields);
  2796. // There are 10 entities of this bundle.
  2797. $query = new EntityFieldQuery();
  2798. $found = $query
  2799. ->fieldCondition($field)
  2800. ->entityCondition('bundle', $bundle)
  2801. ->execute();
  2802. $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');
  2803. // Delete the instance.
  2804. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2805. field_delete_instance($instance);
  2806. // The instance still exists, deleted.
  2807. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2808. $this->assertEqual(count($instances), 1, 'There is one deleted instance');
  2809. $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');
  2810. // There are 0 entities of this bundle with non-deleted data.
  2811. $query = new EntityFieldQuery();
  2812. $found = $query
  2813. ->fieldCondition($field)
  2814. ->entityCondition('bundle', $bundle)
  2815. ->execute();
  2816. $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');
  2817. // There are 10 entities of this bundle when deleted fields are allowed, and
  2818. // their values are correct.
  2819. $query = new EntityFieldQuery();
  2820. $found = $query
  2821. ->fieldCondition($field)
  2822. ->entityCondition('bundle', $bundle)
  2823. ->deleted(TRUE)
  2824. ->execute();
  2825. field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
  2826. $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
  2827. foreach ($found['test_entity'] as $id => $entity) {
  2828. $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
  2829. }
  2830. }
  2831. /**
  2832. * Verify that field data items and instances are purged when an
  2833. * instance is deleted.
  2834. */
  2835. function testPurgeInstance() {
  2836. // Start recording hook invocations.
  2837. field_test_memorize();
  2838. $bundle = reset($this->bundles);
  2839. $field = reset($this->fields);
  2840. // Delete the instance.
  2841. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2842. field_delete_instance($instance);
  2843. // No field hooks were called.
  2844. $mem = field_test_memorize();
  2845. $this->assertEqual(count($mem), 0, 'No field hooks were called');
  2846. $batch_size = 2;
  2847. for ($count = 8; $count >= 0; $count -= $batch_size) {
  2848. // Purge two entities.
  2849. field_purge_batch($batch_size);
  2850. // There are $count deleted entities left.
  2851. $query = new EntityFieldQuery();
  2852. $found = $query
  2853. ->fieldCondition($field)
  2854. ->entityCondition('bundle', $bundle)
  2855. ->deleted(TRUE)
  2856. ->execute();
  2857. $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
  2858. }
  2859. // Check hooks invocations.
  2860. // - hook_field_load() (multiple hook) should have been called on all
  2861. // entities by pairs of two.
  2862. // - hook_field_delete() should have been called once for each entity in the
  2863. // bundle.
  2864. $actual_hooks = field_test_memorize();
  2865. $hooks = array();
  2866. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2867. foreach (array_chunk($stubs, $batch_size, TRUE) as $chunk) {
  2868. $hooks['field_test_field_load'][] = $chunk;
  2869. }
  2870. foreach ($stubs as $stub) {
  2871. $hooks['field_test_field_delete'][] = $stub;
  2872. }
  2873. $this->checkHooksInvocations($hooks, $actual_hooks);
  2874. // The instance still exists, deleted.
  2875. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2876. $this->assertEqual(count($instances), 1, 'There is one deleted instance');
  2877. // Purge the instance.
  2878. field_purge_batch($batch_size);
  2879. // The instance is gone.
  2880. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2881. $this->assertEqual(count($instances), 0, 'The instance is gone');
  2882. // The field still exists, not deleted, because it has a second instance.
  2883. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
  2884. $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
  2885. }
  2886. /**
  2887. * Verify that fields are preserved and purged correctly as multiple
  2888. * instances are deleted and purged.
  2889. */
  2890. function testPurgeField() {
  2891. // Start recording hook invocations.
  2892. field_test_memorize();
  2893. $field = reset($this->fields);
  2894. // Delete the first instance.
  2895. $bundle = reset($this->bundles);
  2896. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2897. field_delete_instance($instance);
  2898. // Assert that hook_field_delete() was not called yet.
  2899. $mem = field_test_memorize();
  2900. $this->assertEqual(count($mem), 0, 'No field hooks were called.');
  2901. // Purge the data.
  2902. field_purge_batch(10);
  2903. // Check hooks invocations.
  2904. // - hook_field_load() (multiple hook) should have been called once, for all
  2905. // entities in the bundle.
  2906. // - hook_field_delete() should have been called once for each entity in the
  2907. // bundle.
  2908. $actual_hooks = field_test_memorize();
  2909. $hooks = array();
  2910. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2911. $hooks['field_test_field_load'][] = $stubs;
  2912. foreach ($stubs as $stub) {
  2913. $hooks['field_test_field_delete'][] = $stub;
  2914. }
  2915. $this->checkHooksInvocations($hooks, $actual_hooks);
  2916. // Purge again to purge the instance.
  2917. field_purge_batch(0);
  2918. // The field still exists, not deleted.
  2919. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
  2920. $this->assertTrue(isset($fields[$field['id']]) && !$fields[$field['id']]['deleted'], 'The field exists and is not deleted');
  2921. // Delete the second instance.
  2922. $bundle = next($this->bundles);
  2923. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2924. field_delete_instance($instance);
  2925. // Assert that hook_field_delete() was not called yet.
  2926. $mem = field_test_memorize();
  2927. $this->assertEqual(count($mem), 0, 'No field hooks were called.');
  2928. // Purge the data.
  2929. field_purge_batch(10);
  2930. // Check hooks invocations (same as above, for the 2nd bundle).
  2931. $actual_hooks = field_test_memorize();
  2932. $hooks = array();
  2933. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2934. $hooks['field_test_field_load'][] = $stubs;
  2935. foreach ($stubs as $stub) {
  2936. $hooks['field_test_field_delete'][] = $stub;
  2937. }
  2938. $this->checkHooksInvocations($hooks, $actual_hooks);
  2939. // The field still exists, deleted.
  2940. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
  2941. $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');
  2942. // Purge again to purge the instance and the field.
  2943. field_purge_batch(0);
  2944. // The field is gone.
  2945. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
  2946. $this->assertEqual(count($fields), 0, 'The field is purged.');
  2947. }
  2948. }
  2949. /**
  2950. * Tests entity properties.
  2951. */
  2952. class EntityPropertiesTestCase extends FieldTestCase {
  2953. public static function getInfo() {
  2954. return array(
  2955. 'name' => 'Entity properties',
  2956. 'description' => 'Tests entity properties.',
  2957. 'group' => 'Entity API',
  2958. );
  2959. }
  2960. function setUp() {
  2961. parent::setUp('field_test');
  2962. }
  2963. /**
  2964. * Tests label key and label callback of an entity.
  2965. */
  2966. function testEntityLabel() {
  2967. $entity_types = array(
  2968. 'test_entity_no_label',
  2969. 'test_entity_label',
  2970. 'test_entity_label_callback',
  2971. );
  2972. $entity = field_test_create_stub_entity();
  2973. foreach ($entity_types as $entity_type) {
  2974. $label = entity_label($entity_type, $entity);
  2975. switch ($entity_type) {
  2976. case 'test_entity_no_label':
  2977. $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
  2978. break;
  2979. case 'test_entity_label':
  2980. $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
  2981. break;
  2982. case 'test_entity_label_callback':
  2983. $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
  2984. break;
  2985. }
  2986. }
  2987. }
  2988. }