field.test 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409
  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. $info = entity_get_info('test_entity');
  990. $instances = field_info_instances('test_entity', $instance['bundle']);
  991. $this->assertEqual(count($instances), 1, format_string('One instance shows up in info when attached to a bundle on a @label.', array(
  992. '@label' => $info['label']
  993. )));
  994. $this->assertTrue($instance < $instances[$instance['field_name']], t('Instance appears in info correctly'));
  995. // Test a valid entity type but an invalid bundle.
  996. $instances = field_info_instances('test_entity', 'invalid_bundle');
  997. $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'invalid_bundle') returns an empty array.");
  998. // Test invalid entity type and bundle.
  999. $instances = field_info_instances('invalid_entity', $instance['bundle']);
  1000. $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity', 'test_bundle') returns an empty array.");
  1001. // Test invalid entity type, no bundle provided.
  1002. $instances = field_info_instances('invalid_entity');
  1003. $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity') returns an empty array.");
  1004. // Test with an entity type that has no bundles.
  1005. $instances = field_info_instances('user');
  1006. $expected = array('user' => array());
  1007. $this->assertIdentical($instances, $expected, "field_info_instances('user') returns " . var_export($expected, TRUE) . '.');
  1008. $instances = field_info_instances('user', 'user');
  1009. $this->assertIdentical($instances, array(), "field_info_instances('user', 'user') returns an empty array.");
  1010. }
  1011. /**
  1012. * Test that cached field definitions are ready for current runtime context.
  1013. */
  1014. function testFieldPrepare() {
  1015. $field_definition = array(
  1016. 'field_name' => 'field',
  1017. 'type' => 'test_field',
  1018. );
  1019. field_create_field($field_definition);
  1020. // Simulate a stored field definition missing a field setting (e.g. a
  1021. // third-party module adding a new field setting has been enabled, and
  1022. // existing fields do not know the setting yet).
  1023. $data = db_query('SELECT data FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']))->fetchField();
  1024. $data = unserialize($data);
  1025. $data['settings'] = array();
  1026. db_update('field_config')
  1027. ->fields(array('data' => serialize($data)))
  1028. ->condition('field_name', $field_definition['field_name'])
  1029. ->execute();
  1030. field_cache_clear();
  1031. // Read the field back.
  1032. $field = field_info_field($field_definition['field_name']);
  1033. // Check that all expected settings are in place.
  1034. $field_type = field_info_field_types($field_definition['type']);
  1035. $this->assertIdentical($field['settings'], $field_type['settings'], t('All expected default field settings are present.'));
  1036. }
  1037. /**
  1038. * Test that cached instance definitions are ready for current runtime context.
  1039. */
  1040. function testInstancePrepare() {
  1041. $field_definition = array(
  1042. 'field_name' => 'field',
  1043. 'type' => 'test_field',
  1044. );
  1045. field_create_field($field_definition);
  1046. $instance_definition = array(
  1047. 'field_name' => $field_definition['field_name'],
  1048. 'entity_type' => 'test_entity',
  1049. 'bundle' => 'test_bundle',
  1050. );
  1051. field_create_instance($instance_definition);
  1052. // Simulate a stored instance definition missing various settings (e.g. a
  1053. // third-party module adding instance, widget or display settings has been
  1054. // enabled, but existing instances do not know the new settings).
  1055. $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();
  1056. $data = unserialize($data);
  1057. $data['settings'] = array();
  1058. $data['widget']['settings'] = 'unavailable_widget';
  1059. $data['widget']['settings'] = array();
  1060. $data['display']['default']['type'] = 'unavailable_formatter';
  1061. $data['display']['default']['settings'] = array();
  1062. db_update('field_config_instance')
  1063. ->fields(array('data' => serialize($data)))
  1064. ->condition('field_name', $instance_definition['field_name'])
  1065. ->condition('bundle', $instance_definition['bundle'])
  1066. ->execute();
  1067. field_cache_clear();
  1068. // Read the instance back.
  1069. $instance = field_info_instance($instance_definition['entity_type'], $instance_definition['field_name'], $instance_definition['bundle']);
  1070. // Check that all expected instance settings are in place.
  1071. $field_type = field_info_field_types($field_definition['type']);
  1072. $this->assertIdentical($instance['settings'], $field_type['instance_settings'] , t('All expected instance settings are present.'));
  1073. // Check that the default widget is used and expected settings are in place.
  1074. $this->assertIdentical($instance['widget']['type'], $field_type['default_widget'], t('Unavailable widget replaced with default widget.'));
  1075. $widget_type = field_info_widget_types($instance['widget']['type']);
  1076. $this->assertIdentical($instance['widget']['settings'], $widget_type['settings'] , t('All expected widget settings are present.'));
  1077. // Check that display settings are set for the 'default' mode.
  1078. $display = $instance['display']['default'];
  1079. $this->assertIdentical($display['type'], $field_type['default_formatter'], t("Formatter is set for the 'default' view mode"));
  1080. $formatter_type = field_info_formatter_types($display['type']);
  1081. $this->assertIdentical($display['settings'], $formatter_type['settings'] , t("Formatter settings are set for the 'default' view mode"));
  1082. }
  1083. /**
  1084. * Test that instances on disabled entity types are filtered out.
  1085. */
  1086. function testInstanceDisabledEntityType() {
  1087. // For this test the field type and the entity type must be exposed by
  1088. // different modules.
  1089. $field_definition = array(
  1090. 'field_name' => 'field',
  1091. 'type' => 'test_field',
  1092. );
  1093. field_create_field($field_definition);
  1094. $instance_definition = array(
  1095. 'field_name' => 'field',
  1096. 'entity_type' => 'comment',
  1097. 'bundle' => 'comment_node_article',
  1098. );
  1099. field_create_instance($instance_definition);
  1100. // Disable coment module. This clears field_info cache.
  1101. module_disable(array('comment'));
  1102. $this->assertNull(field_info_instance('comment', 'field', 'comment_node_article'), t('No instances are returned on disabled entity types.'));
  1103. }
  1104. /**
  1105. * Test that the field_info settings convenience functions work.
  1106. */
  1107. function testSettingsInfo() {
  1108. $info = field_test_field_info();
  1109. // We need to account for the existence of user_field_info_alter().
  1110. foreach (array_keys($info) as $name) {
  1111. $info[$name]['instance_settings']['user_register_form'] = FALSE;
  1112. }
  1113. foreach ($info as $type => $data) {
  1114. $this->assertIdentical(field_info_field_settings($type), $data['settings'], "field_info_field_settings returns {$type}'s field settings");
  1115. $this->assertIdentical(field_info_instance_settings($type), $data['instance_settings'], "field_info_field_settings returns {$type}'s field instance settings");
  1116. }
  1117. $info = field_test_field_widget_info();
  1118. foreach ($info as $type => $data) {
  1119. $this->assertIdentical(field_info_widget_settings($type), $data['settings'], "field_info_widget_settings returns {$type}'s widget settings");
  1120. }
  1121. $info = field_test_field_formatter_info();
  1122. foreach ($info as $type => $data) {
  1123. $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], "field_info_formatter_settings returns {$type}'s formatter settings");
  1124. }
  1125. }
  1126. }
  1127. class FieldFormTestCase extends FieldTestCase {
  1128. public static function getInfo() {
  1129. return array(
  1130. 'name' => 'Field form tests',
  1131. 'description' => 'Test Field form handling.',
  1132. 'group' => 'Field API',
  1133. );
  1134. }
  1135. function setUp() {
  1136. parent::setUp('field_test');
  1137. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
  1138. $this->drupalLogin($web_user);
  1139. $this->field_single = array('field_name' => 'field_single', 'type' => 'test_field');
  1140. $this->field_multiple = array('field_name' => 'field_multiple', 'type' => 'test_field', 'cardinality' => 4);
  1141. $this->field_unlimited = array('field_name' => 'field_unlimited', 'type' => 'test_field', 'cardinality' => FIELD_CARDINALITY_UNLIMITED);
  1142. $this->instance = array(
  1143. 'entity_type' => 'test_entity',
  1144. 'bundle' => 'test_bundle',
  1145. 'label' => $this->randomName() . '_label',
  1146. 'description' => $this->randomName() . '_description',
  1147. 'weight' => mt_rand(0, 127),
  1148. 'settings' => array(
  1149. 'test_instance_setting' => $this->randomName(),
  1150. ),
  1151. 'widget' => array(
  1152. 'type' => 'test_field_widget',
  1153. 'label' => 'Test Field',
  1154. 'settings' => array(
  1155. 'test_widget_setting' => $this->randomName(),
  1156. )
  1157. )
  1158. );
  1159. }
  1160. function testFieldFormSingle() {
  1161. $this->field = $this->field_single;
  1162. $this->field_name = $this->field['field_name'];
  1163. $this->instance['field_name'] = $this->field_name;
  1164. field_create_field($this->field);
  1165. field_create_instance($this->instance);
  1166. $langcode = LANGUAGE_NONE;
  1167. // Display creation form.
  1168. $this->drupalGet('test-entity/add/test-bundle');
  1169. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget is displayed');
  1170. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1171. // TODO : check that the widget is populated with default value ?
  1172. // Submit with invalid value (field-level validation).
  1173. $edit = array("{$this->field_name}[$langcode][0][value]" => -1);
  1174. $this->drupalPost(NULL, $edit, t('Save'));
  1175. $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->instance['label'])), 'Field validation fails with invalid input.');
  1176. // TODO : check that the correct field is flagged for error.
  1177. // Create an entity
  1178. $value = mt_rand(1, 127);
  1179. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1180. $this->drupalPost(NULL, $edit, t('Save'));
  1181. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1182. $id = $match[1];
  1183. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1184. $entity = field_test_entity_test_load($id);
  1185. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
  1186. // Display edit form.
  1187. $this->drupalGet('test-entity/manage/' . $id . '/edit');
  1188. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", $value, 'Widget is displayed with the correct default value');
  1189. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1190. // Update the entity.
  1191. $value = mt_rand(1, 127);
  1192. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1193. $this->drupalPost(NULL, $edit, t('Save'));
  1194. $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
  1195. $entity = field_test_entity_test_load($id);
  1196. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was updated');
  1197. // Empty the field.
  1198. $value = '';
  1199. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1200. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1201. $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
  1202. $entity = field_test_entity_test_load($id);
  1203. $this->assertIdentical($entity->{$this->field_name}, array(), 'Field was emptied');
  1204. }
  1205. function testFieldFormSingleRequired() {
  1206. $this->field = $this->field_single;
  1207. $this->field_name = $this->field['field_name'];
  1208. $this->instance['field_name'] = $this->field_name;
  1209. $this->instance['required'] = TRUE;
  1210. field_create_field($this->field);
  1211. field_create_instance($this->instance);
  1212. $langcode = LANGUAGE_NONE;
  1213. // Submit with missing required value.
  1214. $edit = array();
  1215. $this->drupalPost('test-entity/add/test-bundle', $edit, t('Save'));
  1216. $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
  1217. // Create an entity
  1218. $value = mt_rand(1, 127);
  1219. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1220. $this->drupalPost(NULL, $edit, t('Save'));
  1221. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1222. $id = $match[1];
  1223. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1224. $entity = field_test_entity_test_load($id);
  1225. $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
  1226. // Edit with missing required value.
  1227. $value = '';
  1228. $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
  1229. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1230. $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
  1231. }
  1232. // function testFieldFormMultiple() {
  1233. // $this->field = $this->field_multiple;
  1234. // $this->field_name = $this->field['field_name'];
  1235. // $this->instance['field_name'] = $this->field_name;
  1236. // field_create_field($this->field);
  1237. // field_create_instance($this->instance);
  1238. // }
  1239. function testFieldFormUnlimited() {
  1240. $this->field = $this->field_unlimited;
  1241. $this->field_name = $this->field['field_name'];
  1242. $this->instance['field_name'] = $this->field_name;
  1243. field_create_field($this->field);
  1244. field_create_instance($this->instance);
  1245. $langcode = LANGUAGE_NONE;
  1246. // Display creation form -> 1 widget.
  1247. $this->drupalGet('test-entity/add/test-bundle');
  1248. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1249. $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
  1250. // Press 'add more' button -> 2 widgets.
  1251. $this->drupalPost(NULL, array(), t('Add another item'));
  1252. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1253. $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
  1254. $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
  1255. // TODO : check that non-field inpurs are preserved ('title')...
  1256. // Yet another time so that we can play with more values -> 3 widgets.
  1257. $this->drupalPost(NULL, array(), t('Add another item'));
  1258. // Prepare values and weights.
  1259. $count = 3;
  1260. $delta_range = $count - 1;
  1261. $values = $weights = $pattern = $expected_values = $edit = array();
  1262. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1263. // Assign unique random values and weights.
  1264. do {
  1265. $value = mt_rand(1, 127);
  1266. } while (in_array($value, $values));
  1267. do {
  1268. $weight = mt_rand(-$delta_range, $delta_range);
  1269. } while (in_array($weight, $weights));
  1270. $edit["$this->field_name[$langcode][$delta][value]"] = $value;
  1271. $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
  1272. // We'll need three slightly different formats to check the values.
  1273. $values[$delta] = $value;
  1274. $weights[$delta] = $weight;
  1275. $field_values[$weight]['value'] = (string) $value;
  1276. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  1277. }
  1278. // Press 'add more' button -> 4 widgets
  1279. $this->drupalPost(NULL, $edit, t('Add another item'));
  1280. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1281. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  1282. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  1283. }
  1284. ksort($pattern);
  1285. $pattern = implode('.*', array_values($pattern));
  1286. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  1287. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
  1288. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
  1289. $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  1290. // Submit the form and create the entity.
  1291. $this->drupalPost(NULL, $edit, t('Save'));
  1292. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1293. $id = $match[1];
  1294. $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
  1295. $entity = field_test_entity_test_load($id);
  1296. ksort($field_values);
  1297. $field_values = array_values($field_values);
  1298. $this->assertIdentical($entity->{$this->field_name}[$langcode], $field_values, 'Field values were saved in the correct order');
  1299. // Display edit form: check that the expected number of widgets is
  1300. // displayed, with correct values change values, reorder, leave an empty
  1301. // value in the middle.
  1302. // Submit: check that the entity is updated with correct values
  1303. // Re-submit: check that the field can be emptied.
  1304. // Test with several multiple fields in a form
  1305. }
  1306. /**
  1307. * Tests widget handling of multiple required radios.
  1308. */
  1309. function testFieldFormMultivalueWithRequiredRadio() {
  1310. // Create a multivalue test field.
  1311. $this->field = $this->field_unlimited;
  1312. $this->field_name = $this->field['field_name'];
  1313. $this->instance['field_name'] = $this->field_name;
  1314. field_create_field($this->field);
  1315. field_create_instance($this->instance);
  1316. $langcode = LANGUAGE_NONE;
  1317. // Add a required radio field.
  1318. field_create_field(array(
  1319. 'field_name' => 'required_radio_test',
  1320. 'type' => 'list_text',
  1321. 'settings' => array(
  1322. 'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
  1323. ),
  1324. ));
  1325. field_create_instance(array(
  1326. 'field_name' => 'required_radio_test',
  1327. 'entity_type' => 'test_entity',
  1328. 'bundle' => 'test_bundle',
  1329. 'required' => TRUE,
  1330. 'widget' => array(
  1331. 'type' => 'options_buttons',
  1332. ),
  1333. ));
  1334. // Display creation form.
  1335. $this->drupalGet('test-entity/add/test-bundle');
  1336. // Press the 'Add more' button.
  1337. $this->drupalPost(NULL, array(), t('Add another item'));
  1338. // Verify that no error is thrown by the radio element.
  1339. $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
  1340. // Verify that the widget is added.
  1341. $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
  1342. $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
  1343. $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
  1344. }
  1345. function testFieldFormJSAddMore() {
  1346. $this->field = $this->field_unlimited;
  1347. $this->field_name = $this->field['field_name'];
  1348. $this->instance['field_name'] = $this->field_name;
  1349. field_create_field($this->field);
  1350. field_create_instance($this->instance);
  1351. $langcode = LANGUAGE_NONE;
  1352. // Display creation form -> 1 widget.
  1353. $this->drupalGet('test-entity/add/test-bundle');
  1354. // Press 'add more' button a couple times -> 3 widgets.
  1355. // drupalPostAJAX() will not work iteratively, so we add those through
  1356. // non-JS submission.
  1357. $this->drupalPost(NULL, array(), t('Add another item'));
  1358. $this->drupalPost(NULL, array(), t('Add another item'));
  1359. // Prepare values and weights.
  1360. $count = 3;
  1361. $delta_range = $count - 1;
  1362. $values = $weights = $pattern = $expected_values = $edit = array();
  1363. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1364. // Assign unique random values and weights.
  1365. do {
  1366. $value = mt_rand(1, 127);
  1367. } while (in_array($value, $values));
  1368. do {
  1369. $weight = mt_rand(-$delta_range, $delta_range);
  1370. } while (in_array($weight, $weights));
  1371. $edit["$this->field_name[$langcode][$delta][value]"] = $value;
  1372. $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
  1373. // We'll need three slightly different formats to check the values.
  1374. $values[$delta] = $value;
  1375. $weights[$delta] = $weight;
  1376. $field_values[$weight]['value'] = (string) $value;
  1377. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  1378. }
  1379. // Press 'add more' button through Ajax, and place the expected HTML result
  1380. // as the tested content.
  1381. $commands = $this->drupalPostAJAX(NULL, $edit, $this->field_name . '_add_more');
  1382. $this->content = $commands[1]['data'];
  1383. for ($delta = 0; $delta <= $delta_range; $delta++) {
  1384. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  1385. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  1386. }
  1387. ksort($pattern);
  1388. $pattern = implode('.*', array_values($pattern));
  1389. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  1390. $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
  1391. $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
  1392. $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  1393. }
  1394. /**
  1395. * Tests widgets handling multiple values.
  1396. */
  1397. function testFieldFormMultipleWidget() {
  1398. // Create a field with fixed cardinality and an instance using a multiple
  1399. // widget.
  1400. $this->field = $this->field_multiple;
  1401. $this->field_name = $this->field['field_name'];
  1402. $this->instance['field_name'] = $this->field_name;
  1403. $this->instance['widget']['type'] = 'test_field_widget_multiple';
  1404. field_create_field($this->field);
  1405. field_create_instance($this->instance);
  1406. $langcode = LANGUAGE_NONE;
  1407. // Display creation form.
  1408. $this->drupalGet('test-entity/add/test-bundle');
  1409. $this->assertFieldByName("{$this->field_name}[$langcode]", '', t('Widget is displayed.'));
  1410. // Create entity with three values.
  1411. $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3');
  1412. $this->drupalPost(NULL, $edit, t('Save'));
  1413. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1414. $id = $match[1];
  1415. // Check that the values were saved.
  1416. $entity_init = field_test_create_stub_entity($id);
  1417. $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
  1418. // Display the form, check that the values are correctly filled in.
  1419. $this->drupalGet('test-entity/manage/' . $id . '/edit');
  1420. $this->assertFieldByName("{$this->field_name}[$langcode]", '1, 2, 3', t('Widget is displayed.'));
  1421. // Submit the form with more values than the field accepts.
  1422. $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3, 4, 5');
  1423. $this->drupalPost(NULL, $edit, t('Save'));
  1424. $this->assertRaw('this field cannot hold more than 4 values', t('Form validation failed.'));
  1425. // Check that the field values were not submitted.
  1426. $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
  1427. }
  1428. /**
  1429. * Tests fields with no 'edit' access.
  1430. */
  1431. function testFieldFormAccess() {
  1432. // Create a "regular" field.
  1433. $field = $this->field_single;
  1434. $field_name = $field['field_name'];
  1435. $instance = $this->instance;
  1436. $instance['field_name'] = $field_name;
  1437. field_create_field($field);
  1438. field_create_instance($instance);
  1439. // Create a field with no edit access - see field_test_field_access().
  1440. $field_no_access = array(
  1441. 'field_name' => 'field_no_edit_access',
  1442. 'type' => 'test_field',
  1443. );
  1444. $field_name_no_access = $field_no_access['field_name'];
  1445. $instance_no_access = array(
  1446. 'field_name' => $field_name_no_access,
  1447. 'entity_type' => 'test_entity',
  1448. 'bundle' => 'test_bundle',
  1449. 'default_value' => array(0 => array('value' => 99)),
  1450. );
  1451. field_create_field($field_no_access);
  1452. field_create_instance($instance_no_access);
  1453. $langcode = LANGUAGE_NONE;
  1454. // Test that the form structure includes full information for each delta
  1455. // apart from #access.
  1456. $entity_type = 'test_entity';
  1457. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  1458. $form = array();
  1459. $form_state = form_state_defaults();
  1460. field_attach_form($entity_type, $entity, $form, $form_state);
  1461. $this->assertEqual($form[$field_name_no_access][$langcode][0]['value']['#entity_type'], $entity_type, 'The correct entity type is set in the field structure.');
  1462. $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
  1463. // Display creation form.
  1464. $this->drupalGet('test-entity/add/test-bundle');
  1465. $this->assertNoFieldByName("{$field_name_no_access}[$langcode][0][value]", '', t('Widget is not displayed if field access is denied.'));
  1466. // Create entity.
  1467. $edit = array("{$field_name}[$langcode][0][value]" => 1);
  1468. $this->drupalPost(NULL, $edit, t('Save'));
  1469. preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
  1470. $id = $match[1];
  1471. // Check that the default value was saved.
  1472. $entity = field_test_entity_test_load($id);
  1473. $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, t('Default value was saved for the field with no edit access.'));
  1474. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 1, t('Entered value vas saved for the field with edit access.'));
  1475. // Create a new revision.
  1476. $edit = array("{$field_name}[$langcode][0][value]" => 2, 'revision' => TRUE);
  1477. $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
  1478. // Check that the new revision has the expected values.
  1479. $entity = field_test_entity_test_load($id);
  1480. $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.'));
  1481. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));
  1482. // Check that the revision is also saved in the revisions table.
  1483. $entity = field_test_entity_test_load($id, $entity->ftvid);
  1484. $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.'));
  1485. $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, t('New revision has the expected value for the field with edit access.'));
  1486. }
  1487. /**
  1488. * Tests Field API form integration within a subform.
  1489. */
  1490. function testNestedFieldForm() {
  1491. // Add two instances on the 'test_bundle'
  1492. field_create_field($this->field_single);
  1493. field_create_field($this->field_unlimited);
  1494. $this->instance['field_name'] = 'field_single';
  1495. $this->instance['label'] = 'Single field';
  1496. field_create_instance($this->instance);
  1497. $this->instance['field_name'] = 'field_unlimited';
  1498. $this->instance['label'] = 'Unlimited field';
  1499. field_create_instance($this->instance);
  1500. // Create two entities.
  1501. $entity_1 = field_test_create_stub_entity(1, 1);
  1502. $entity_1->is_new = TRUE;
  1503. $entity_1->field_single[LANGUAGE_NONE][] = array('value' => 0);
  1504. $entity_1->field_unlimited[LANGUAGE_NONE][] = array('value' => 1);
  1505. field_test_entity_save($entity_1);
  1506. $entity_2 = field_test_create_stub_entity(2, 2);
  1507. $entity_2->is_new = TRUE;
  1508. $entity_2->field_single[LANGUAGE_NONE][] = array('value' => 10);
  1509. $entity_2->field_unlimited[LANGUAGE_NONE][] = array('value' => 11);
  1510. field_test_entity_save($entity_2);
  1511. // Display the 'combined form'.
  1512. $this->drupalGet('test-entity/nested/1/2');
  1513. $this->assertFieldByName('field_single[und][0][value]', 0, t('Entity 1: field_single value appears correctly is the form.'));
  1514. $this->assertFieldByName('field_unlimited[und][0][value]', 1, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
  1515. $this->assertFieldByName('entity_2[field_single][und][0][value]', 10, t('Entity 2: field_single value appears correctly is the form.'));
  1516. $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 11, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));
  1517. // Submit the form and check that the entities are updated accordingly.
  1518. $edit = array(
  1519. 'field_single[und][0][value]' => 1,
  1520. 'field_unlimited[und][0][value]' => 2,
  1521. 'field_unlimited[und][1][value]' => 3,
  1522. 'entity_2[field_single][und][0][value]' => 11,
  1523. 'entity_2[field_unlimited][und][0][value]' => 12,
  1524. 'entity_2[field_unlimited][und][1][value]' => 13,
  1525. );
  1526. $this->drupalPost(NULL, $edit, t('Save'));
  1527. field_cache_clear();
  1528. $entity_1 = field_test_create_stub_entity(1);
  1529. $entity_2 = field_test_create_stub_entity(2);
  1530. $this->assertFieldValues($entity_1, 'field_single', LANGUAGE_NONE, array(1));
  1531. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(2, 3));
  1532. $this->assertFieldValues($entity_2, 'field_single', LANGUAGE_NONE, array(11));
  1533. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(12, 13));
  1534. // Submit invalid values and check that errors are reported on the
  1535. // correct widgets.
  1536. $edit = array(
  1537. 'field_unlimited[und][1][value]' => -1,
  1538. );
  1539. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1540. $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 1: the field validation error was reported.'));
  1541. $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-und-1-value'));
  1542. $this->assertTrue($error_field, t('Entity 1: the error was flagged on the correct element.'));
  1543. $edit = array(
  1544. 'entity_2[field_unlimited][und][1][value]' => -1,
  1545. );
  1546. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1547. $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), t('Entity 2: the field validation error was reported.'));
  1548. $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-und-1-value'));
  1549. $this->assertTrue($error_field, t('Entity 2: the error was flagged on the correct element.'));
  1550. // Test that reordering works on both entities.
  1551. $edit = array(
  1552. 'field_unlimited[und][0][_weight]' => 0,
  1553. 'field_unlimited[und][1][_weight]' => -1,
  1554. 'entity_2[field_unlimited][und][0][_weight]' => 0,
  1555. 'entity_2[field_unlimited][und][1][_weight]' => -1,
  1556. );
  1557. $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
  1558. field_cache_clear();
  1559. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
  1560. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 12));
  1561. // Test the 'add more' buttons. Only Ajax submission is tested, because
  1562. // the two 'add more' buttons present in the form have the same #value,
  1563. // which confuses drupalPost().
  1564. // 'Add more' button in the first entity:
  1565. $this->drupalGet('test-entity/nested/1/2');
  1566. $this->drupalPostAJAX(NULL, array(), 'field_unlimited_add_more');
  1567. $this->assertFieldByName('field_unlimited[und][0][value]', 3, t('Entity 1: field_unlimited value 0 appears correctly is the form.'));
  1568. $this->assertFieldByName('field_unlimited[und][1][value]', 2, t('Entity 1: field_unlimited value 1 appears correctly is the form.'));
  1569. $this->assertFieldByName('field_unlimited[und][2][value]', '', t('Entity 1: field_unlimited value 2 appears correctly is the form.'));
  1570. $this->assertFieldByName('field_unlimited[und][3][value]', '', t('Entity 1: an empty widget was added for field_unlimited value 3.'));
  1571. // 'Add more' button in the first entity (changing field values):
  1572. $edit = array(
  1573. 'entity_2[field_unlimited][und][0][value]' => 13,
  1574. 'entity_2[field_unlimited][und][1][value]' => 14,
  1575. 'entity_2[field_unlimited][und][2][value]' => 15,
  1576. );
  1577. $this->drupalPostAJAX(NULL, $edit, 'entity_2_field_unlimited_add_more');
  1578. $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 13, t('Entity 2: field_unlimited value 0 appears correctly is the form.'));
  1579. $this->assertFieldByName('entity_2[field_unlimited][und][1][value]', 14, t('Entity 2: field_unlimited value 1 appears correctly is the form.'));
  1580. $this->assertFieldByName('entity_2[field_unlimited][und][2][value]', 15, t('Entity 2: field_unlimited value 2 appears correctly is the form.'));
  1581. $this->assertFieldByName('entity_2[field_unlimited][und][3][value]', '', t('Entity 2: an empty widget was added for field_unlimited value 3.'));
  1582. // Save the form and check values are saved correclty.
  1583. $this->drupalPost(NULL, array(), t('Save'));
  1584. field_cache_clear();
  1585. $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
  1586. $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 14, 15));
  1587. }
  1588. }
  1589. class FieldDisplayAPITestCase extends FieldTestCase {
  1590. public static function getInfo() {
  1591. return array(
  1592. 'name' => 'Field Display API tests',
  1593. 'description' => 'Test the display API.',
  1594. 'group' => 'Field API',
  1595. );
  1596. }
  1597. function setUp() {
  1598. parent::setUp('field_test');
  1599. // Create a field and instance.
  1600. $this->field_name = 'test_field';
  1601. $this->label = $this->randomName();
  1602. $this->cardinality = 4;
  1603. $this->field = array(
  1604. 'field_name' => $this->field_name,
  1605. 'type' => 'test_field',
  1606. 'cardinality' => $this->cardinality,
  1607. );
  1608. $this->instance = array(
  1609. 'field_name' => $this->field_name,
  1610. 'entity_type' => 'test_entity',
  1611. 'bundle' => 'test_bundle',
  1612. 'label' => $this->label,
  1613. 'display' => array(
  1614. 'default' => array(
  1615. 'type' => 'field_test_default',
  1616. 'settings' => array(
  1617. 'test_formatter_setting' => $this->randomName(),
  1618. ),
  1619. ),
  1620. 'teaser' => array(
  1621. 'type' => 'field_test_default',
  1622. 'settings' => array(
  1623. 'test_formatter_setting' => $this->randomName(),
  1624. ),
  1625. ),
  1626. ),
  1627. );
  1628. field_create_field($this->field);
  1629. field_create_instance($this->instance);
  1630. // Create an entity with values.
  1631. $this->values = $this->_generateTestFieldValues($this->cardinality);
  1632. $this->entity = field_test_create_stub_entity();
  1633. $this->is_new = TRUE;
  1634. $this->entity->{$this->field_name}[LANGUAGE_NONE] = $this->values;
  1635. field_test_entity_save($this->entity);
  1636. }
  1637. /**
  1638. * Test the field_view_field() function.
  1639. */
  1640. function testFieldViewField() {
  1641. // No display settings: check that default display settings are used.
  1642. $output = field_view_field('test_entity', $this->entity, $this->field_name);
  1643. $this->drupalSetContent(drupal_render($output));
  1644. $settings = field_info_formatter_settings('field_test_default');
  1645. $setting = $settings['test_formatter_setting'];
  1646. $this->assertText($this->label, t('Label was displayed.'));
  1647. foreach ($this->values as $delta => $value) {
  1648. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1649. }
  1650. // Check that explicit display settings are used.
  1651. $display = array(
  1652. 'label' => 'hidden',
  1653. 'type' => 'field_test_multiple',
  1654. 'settings' => array(
  1655. 'test_formatter_setting_multiple' => $this->randomName(),
  1656. 'alter' => TRUE,
  1657. ),
  1658. );
  1659. $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
  1660. $this->drupalSetContent(drupal_render($output));
  1661. $setting = $display['settings']['test_formatter_setting_multiple'];
  1662. $this->assertNoText($this->label, t('Label was not displayed.'));
  1663. $this->assertText('field_test_field_attach_view_alter', t('Alter fired, display passed.'));
  1664. $array = array();
  1665. foreach ($this->values as $delta => $value) {
  1666. $array[] = $delta . ':' . $value['value'];
  1667. }
  1668. $this->assertText($setting . '|' . implode('|', $array), t('Values were displayed with expected setting.'));
  1669. // Check the prepare_view steps are invoked.
  1670. $display = array(
  1671. 'label' => 'hidden',
  1672. 'type' => 'field_test_with_prepare_view',
  1673. 'settings' => array(
  1674. 'test_formatter_setting_additional' => $this->randomName(),
  1675. ),
  1676. );
  1677. $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
  1678. $view = drupal_render($output);
  1679. $this->drupalSetContent($view);
  1680. $setting = $display['settings']['test_formatter_setting_additional'];
  1681. $this->assertNoText($this->label, t('Label was not displayed.'));
  1682. $this->assertNoText('field_test_field_attach_view_alter', t('Alter not fired.'));
  1683. foreach ($this->values as $delta => $value) {
  1684. $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1685. }
  1686. // View mode: check that display settings specified in the instance are
  1687. // used.
  1688. $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
  1689. $this->drupalSetContent(drupal_render($output));
  1690. $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
  1691. $this->assertText($this->label, t('Label was displayed.'));
  1692. foreach ($this->values as $delta => $value) {
  1693. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1694. }
  1695. // Unknown view mode: check that display settings for 'default' view mode
  1696. // are used.
  1697. $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
  1698. $this->drupalSetContent(drupal_render($output));
  1699. $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
  1700. $this->assertText($this->label, t('Label was displayed.'));
  1701. foreach ($this->values as $delta => $value) {
  1702. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1703. }
  1704. }
  1705. /**
  1706. * Test the field_view_value() function.
  1707. */
  1708. function testFieldViewValue() {
  1709. // No display settings: check that default display settings are used.
  1710. $settings = field_info_formatter_settings('field_test_default');
  1711. $setting = $settings['test_formatter_setting'];
  1712. foreach ($this->values as $delta => $value) {
  1713. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1714. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
  1715. $this->drupalSetContent(drupal_render($output));
  1716. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1717. }
  1718. // Check that explicit display settings are used.
  1719. $display = array(
  1720. 'type' => 'field_test_multiple',
  1721. 'settings' => array(
  1722. 'test_formatter_setting_multiple' => $this->randomName(),
  1723. ),
  1724. );
  1725. $setting = $display['settings']['test_formatter_setting_multiple'];
  1726. $array = array();
  1727. foreach ($this->values as $delta => $value) {
  1728. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1729. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
  1730. $this->drupalSetContent(drupal_render($output));
  1731. $this->assertText($setting . '|0:' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1732. }
  1733. // Check that prepare_view steps are invoked.
  1734. $display = array(
  1735. 'type' => 'field_test_with_prepare_view',
  1736. 'settings' => array(
  1737. 'test_formatter_setting_additional' => $this->randomName(),
  1738. ),
  1739. );
  1740. $setting = $display['settings']['test_formatter_setting_additional'];
  1741. $array = array();
  1742. foreach ($this->values as $delta => $value) {
  1743. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1744. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
  1745. $this->drupalSetContent(drupal_render($output));
  1746. $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1747. }
  1748. // View mode: check that display settings specified in the instance are
  1749. // used.
  1750. $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
  1751. foreach ($this->values as $delta => $value) {
  1752. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1753. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
  1754. $this->drupalSetContent(drupal_render($output));
  1755. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1756. }
  1757. // Unknown view mode: check that display settings for 'default' view mode
  1758. // are used.
  1759. $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
  1760. foreach ($this->values as $delta => $value) {
  1761. $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
  1762. $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
  1763. $this->drupalSetContent(drupal_render($output));
  1764. $this->assertText($setting . '|' . $value['value'], t('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
  1765. }
  1766. }
  1767. }
  1768. class FieldCrudTestCase extends FieldTestCase {
  1769. public static function getInfo() {
  1770. return array(
  1771. 'name' => 'Field CRUD tests',
  1772. 'description' => 'Test field create, read, update, and delete.',
  1773. 'group' => 'Field API',
  1774. );
  1775. }
  1776. function setUp() {
  1777. // field_update_field() tests use number.module
  1778. parent::setUp('field_test', 'number');
  1779. }
  1780. // TODO : test creation with
  1781. // - a full fledged $field structure, check that all the values are there
  1782. // - a minimal $field structure, check all default values are set
  1783. // defer actual $field comparison to a helper function, used for the two cases above
  1784. /**
  1785. * Test the creation of a field.
  1786. */
  1787. function testCreateField() {
  1788. $field_definition = array(
  1789. 'field_name' => 'field_2',
  1790. 'type' => 'test_field',
  1791. );
  1792. field_test_memorize();
  1793. $field_definition = field_create_field($field_definition);
  1794. $mem = field_test_memorize();
  1795. $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');
  1796. // Read the raw record from the {field_config_instance} table.
  1797. $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
  1798. $record = $result->fetchAssoc();
  1799. $record['data'] = unserialize($record['data']);
  1800. // Ensure that basic properties are preserved.
  1801. $this->assertEqual($record['field_name'], $field_definition['field_name'], t('The field name is properly saved.'));
  1802. $this->assertEqual($record['type'], $field_definition['type'], t('The field type is properly saved.'));
  1803. // Ensure that cardinality defaults to 1.
  1804. $this->assertEqual($record['cardinality'], 1, t('Cardinality defaults to 1.'));
  1805. // Ensure that default settings are present.
  1806. $field_type = field_info_field_types($field_definition['type']);
  1807. $this->assertIdentical($record['data']['settings'], $field_type['settings'], t('Default field settings have been written.'));
  1808. // Ensure that default storage was set.
  1809. $this->assertEqual($record['storage_type'], variable_get('field_storage_default'), t('The field type is properly saved.'));
  1810. // Guarantee that the name is unique.
  1811. try {
  1812. field_create_field($field_definition);
  1813. $this->fail(t('Cannot create two fields with the same name.'));
  1814. }
  1815. catch (FieldException $e) {
  1816. $this->pass(t('Cannot create two fields with the same name.'));
  1817. }
  1818. // Check that field type is required.
  1819. try {
  1820. $field_definition = array(
  1821. 'field_name' => 'field_1',
  1822. );
  1823. field_create_field($field_definition);
  1824. $this->fail(t('Cannot create a field with no type.'));
  1825. }
  1826. catch (FieldException $e) {
  1827. $this->pass(t('Cannot create a field with no type.'));
  1828. }
  1829. // Check that field name is required.
  1830. try {
  1831. $field_definition = array(
  1832. 'type' => 'test_field'
  1833. );
  1834. field_create_field($field_definition);
  1835. $this->fail(t('Cannot create an unnamed field.'));
  1836. }
  1837. catch (FieldException $e) {
  1838. $this->pass(t('Cannot create an unnamed field.'));
  1839. }
  1840. // Check that field name must start with a letter or _.
  1841. try {
  1842. $field_definition = array(
  1843. 'field_name' => '2field_2',
  1844. 'type' => 'test_field',
  1845. );
  1846. field_create_field($field_definition);
  1847. $this->fail(t('Cannot create a field with a name starting with a digit.'));
  1848. }
  1849. catch (FieldException $e) {
  1850. $this->pass(t('Cannot create a field with a name starting with a digit.'));
  1851. }
  1852. // Check that field name must only contain lowercase alphanumeric or _.
  1853. try {
  1854. $field_definition = array(
  1855. 'field_name' => 'field#_3',
  1856. 'type' => 'test_field',
  1857. );
  1858. field_create_field($field_definition);
  1859. $this->fail(t('Cannot create a field with a name containing an illegal character.'));
  1860. }
  1861. catch (FieldException $e) {
  1862. $this->pass(t('Cannot create a field with a name containing an illegal character.'));
  1863. }
  1864. // Check that field name cannot be longer than 32 characters long.
  1865. try {
  1866. $field_definition = array(
  1867. 'field_name' => '_12345678901234567890123456789012',
  1868. 'type' => 'test_field',
  1869. );
  1870. field_create_field($field_definition);
  1871. $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
  1872. }
  1873. catch (FieldException $e) {
  1874. $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
  1875. }
  1876. // Check that field name can not be an entity key.
  1877. // "ftvid" is known as an entity key from the "test_entity" type.
  1878. try {
  1879. $field_definition = array(
  1880. 'type' => 'test_field',
  1881. 'field_name' => 'ftvid',
  1882. );
  1883. $field = field_create_field($field_definition);
  1884. $this->fail(t('Cannot create a field bearing the name of an entity key.'));
  1885. }
  1886. catch (FieldException $e) {
  1887. $this->pass(t('Cannot create a field bearing the name of an entity key.'));
  1888. }
  1889. }
  1890. /**
  1891. * Test failure to create a field.
  1892. */
  1893. function testCreateFieldFail() {
  1894. $field_name = 'duplicate';
  1895. $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
  1896. $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();
  1897. // The field does not appear in field_config.
  1898. $count = $query->execute()->fetchField();
  1899. $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
  1900. // Try to create the field.
  1901. try {
  1902. $field = field_create_field($field_definition);
  1903. $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
  1904. }
  1905. catch (Exception $e) {
  1906. $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
  1907. }
  1908. // The field does not appear in field_config.
  1909. $count = $query->execute()->fetchField();
  1910. $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
  1911. }
  1912. /**
  1913. * Test reading back a field definition.
  1914. */
  1915. function testReadField() {
  1916. $field_definition = array(
  1917. 'field_name' => 'field_1',
  1918. 'type' => 'test_field',
  1919. );
  1920. field_create_field($field_definition);
  1921. // Read the field back.
  1922. $field = field_read_field($field_definition['field_name']);
  1923. $this->assertTrue($field_definition < $field, t('The field was properly read.'));
  1924. }
  1925. /**
  1926. * Test creation of indexes on data column.
  1927. */
  1928. function testFieldIndexes() {
  1929. // Check that indexes specified by the field type are used by default.
  1930. $field_definition = array(
  1931. 'field_name' => 'field_1',
  1932. 'type' => 'test_field',
  1933. );
  1934. field_create_field($field_definition);
  1935. $field = field_read_field($field_definition['field_name']);
  1936. $expected_indexes = array('value' => array('value'));
  1937. $this->assertEqual($field['indexes'], $expected_indexes, t('Field type indexes saved by default'));
  1938. // Check that indexes specified by the field definition override the field
  1939. // type indexes.
  1940. $field_definition = array(
  1941. 'field_name' => 'field_2',
  1942. 'type' => 'test_field',
  1943. 'indexes' => array(
  1944. 'value' => array(),
  1945. ),
  1946. );
  1947. field_create_field($field_definition);
  1948. $field = field_read_field($field_definition['field_name']);
  1949. $expected_indexes = array('value' => array());
  1950. $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes override field type indexes'));
  1951. // Check that indexes specified by the field definition add to the field
  1952. // type indexes.
  1953. $field_definition = array(
  1954. 'field_name' => 'field_3',
  1955. 'type' => 'test_field',
  1956. 'indexes' => array(
  1957. 'value_2' => array('value'),
  1958. ),
  1959. );
  1960. field_create_field($field_definition);
  1961. $field = field_read_field($field_definition['field_name']);
  1962. $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
  1963. $this->assertEqual($field['indexes'], $expected_indexes, t('Field definition indexes are merged with field type indexes'));
  1964. }
  1965. /**
  1966. * Test the deletion of a field.
  1967. */
  1968. function testDeleteField() {
  1969. // TODO: Also test deletion of the data stored in the field ?
  1970. // Create two fields (so we can test that only one is deleted).
  1971. $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
  1972. field_create_field($this->field);
  1973. $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
  1974. field_create_field($this->another_field);
  1975. // Create instances for each.
  1976. $this->instance_definition = array(
  1977. 'field_name' => $this->field['field_name'],
  1978. 'entity_type' => 'test_entity',
  1979. 'bundle' => 'test_bundle',
  1980. 'widget' => array(
  1981. 'type' => 'test_field_widget',
  1982. ),
  1983. );
  1984. field_create_instance($this->instance_definition);
  1985. $this->another_instance_definition = $this->instance_definition;
  1986. $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
  1987. field_create_instance($this->another_instance_definition);
  1988. // Test that the first field is not deleted, and then delete it.
  1989. $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
  1990. $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field is not marked for deletion.'));
  1991. field_delete_field($this->field['field_name']);
  1992. // Make sure that the field is marked as deleted when it is specifically
  1993. // loaded.
  1994. $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
  1995. $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion.'));
  1996. // Make sure that this field's instance is marked as deleted when it is
  1997. // specifically loaded.
  1998. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  1999. $this->assertTrue(!empty($instance['deleted']), t('An instance for a deleted field is marked for deletion.'));
  2000. // Try to load the field normally and make sure it does not show up.
  2001. $field = field_read_field($this->field['field_name']);
  2002. $this->assertTrue(empty($field), t('A deleted field is not loaded by default.'));
  2003. // Try to load the instance normally and make sure it does not show up.
  2004. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2005. $this->assertTrue(empty($instance), t('An instance for a deleted field is not loaded by default.'));
  2006. // Make sure the other field (and its field instance) are not deleted.
  2007. $another_field = field_read_field($this->another_field['field_name']);
  2008. $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), t('A non-deleted field is not marked for deletion.'));
  2009. $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
  2010. $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('An instance of a non-deleted field is not marked for deletion.'));
  2011. // Try to create a new field the same name as a deleted field and
  2012. // write data into it.
  2013. field_create_field($this->field);
  2014. field_create_instance($this->instance_definition);
  2015. $field = field_read_field($this->field['field_name']);
  2016. $this->assertTrue(!empty($field) && empty($field['deleted']), t('A new field with a previously used name is created.'));
  2017. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2018. $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new instance for a previously used field name is created.'));
  2019. // Save an entity with data for the field
  2020. $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
  2021. $langcode = LANGUAGE_NONE;
  2022. $values[0]['value'] = mt_rand(1, 127);
  2023. $entity->{$field['field_name']}[$langcode] = $values;
  2024. $entity_type = 'test_entity';
  2025. field_attach_insert('test_entity', $entity);
  2026. // Verify the field is present on load
  2027. $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
  2028. field_attach_load($entity_type, array(0 => $entity));
  2029. $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
  2030. foreach ($values as $delta => $value) {
  2031. $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
  2032. }
  2033. }
  2034. function testUpdateNonExistentField() {
  2035. $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
  2036. try {
  2037. field_update_field($test_field);
  2038. $this->fail(t('Cannot update a field that does not exist.'));
  2039. }
  2040. catch (FieldException $e) {
  2041. $this->pass(t('Cannot update a field that does not exist.'));
  2042. }
  2043. }
  2044. function testUpdateFieldType() {
  2045. $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
  2046. $field = field_create_field($field);
  2047. $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
  2048. try {
  2049. field_update_field($test_field);
  2050. $this->fail(t('Cannot update a field to a different type.'));
  2051. }
  2052. catch (FieldException $e) {
  2053. $this->pass(t('Cannot update a field to a different type.'));
  2054. }
  2055. }
  2056. /**
  2057. * Test updating a field.
  2058. */
  2059. function testUpdateField() {
  2060. // Create a field with a defined cardinality, so that we can ensure it's
  2061. // respected. Since cardinality enforcement is consistent across database
  2062. // systems, it makes a good test case.
  2063. $cardinality = 4;
  2064. $field_definition = array(
  2065. 'field_name' => 'field_update',
  2066. 'type' => 'test_field',
  2067. 'cardinality' => $cardinality,
  2068. );
  2069. $field_definition = field_create_field($field_definition);
  2070. $instance = array(
  2071. 'field_name' => 'field_update',
  2072. 'entity_type' => 'test_entity',
  2073. 'bundle' => 'test_bundle',
  2074. );
  2075. $instance = field_create_instance($instance);
  2076. do {
  2077. // We need a unique ID for our entity. $cardinality will do.
  2078. $id = $cardinality;
  2079. $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
  2080. // Fill in the entity with more values than $cardinality.
  2081. for ($i = 0; $i < 20; $i++) {
  2082. $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
  2083. }
  2084. // Save the entity.
  2085. field_attach_insert('test_entity', $entity);
  2086. // Load back and assert there are $cardinality number of values.
  2087. $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
  2088. field_attach_load('test_entity', array($id => $entity));
  2089. $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
  2090. // Now check the values themselves.
  2091. for ($delta = 0; $delta < $cardinality; $delta++) {
  2092. $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
  2093. }
  2094. // Increase $cardinality and set the field cardinality to the new value.
  2095. $field_definition['cardinality'] = ++$cardinality;
  2096. field_update_field($field_definition);
  2097. } while ($cardinality < 6);
  2098. }
  2099. /**
  2100. * Test field type modules forbidding an update.
  2101. */
  2102. function testUpdateFieldForbid() {
  2103. $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
  2104. $field = field_create_field($field);
  2105. $field['settings']['changeable']++;
  2106. try {
  2107. field_update_field($field);
  2108. $this->pass(t("A changeable setting can be updated."));
  2109. }
  2110. catch (FieldException $e) {
  2111. $this->fail(t("An unchangeable setting cannot be updated."));
  2112. }
  2113. $field['settings']['unchangeable']++;
  2114. try {
  2115. field_update_field($field);
  2116. $this->fail(t("An unchangeable setting can be updated."));
  2117. }
  2118. catch (FieldException $e) {
  2119. $this->pass(t("An unchangeable setting cannot be updated."));
  2120. }
  2121. }
  2122. /**
  2123. * Test that fields are properly marked active or inactive.
  2124. */
  2125. function testActive() {
  2126. $field_definition = array(
  2127. 'field_name' => 'field_1',
  2128. 'type' => 'test_field',
  2129. // For this test, we need a storage backend provided by a different
  2130. // module than field_test.module.
  2131. 'storage' => array(
  2132. 'type' => 'field_sql_storage',
  2133. ),
  2134. );
  2135. field_create_field($field_definition);
  2136. // Test disabling and enabling:
  2137. // - the field type module,
  2138. // - the storage module,
  2139. // - both.
  2140. $this->_testActiveHelper($field_definition, array('field_test'));
  2141. $this->_testActiveHelper($field_definition, array('field_sql_storage'));
  2142. $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
  2143. }
  2144. /**
  2145. * Helper function for testActive().
  2146. *
  2147. * Test dependency between a field and a set of modules.
  2148. *
  2149. * @param $field_definition
  2150. * A field definition.
  2151. * @param $modules
  2152. * An aray of module names. The field will be tested to be inactive as long
  2153. * as any of those modules is disabled.
  2154. */
  2155. function _testActiveHelper($field_definition, $modules) {
  2156. $field_name = $field_definition['field_name'];
  2157. // Read the field.
  2158. $field = field_read_field($field_name);
  2159. $this->assertTrue($field_definition <= $field, t('The field was properly read.'));
  2160. module_disable($modules, FALSE);
  2161. $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
  2162. $this->assertTrue(isset($fields[$field_name]) && $field_definition < $field, t('The field is properly read when explicitly fetching inactive fields.'));
  2163. // Re-enable modules one by one, and check that the field is still inactive
  2164. // while some modules remain disabled.
  2165. while ($modules) {
  2166. $field = field_read_field($field_name);
  2167. $this->assertTrue(empty($field), t('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));
  2168. $module = array_shift($modules);
  2169. module_enable(array($module), FALSE);
  2170. }
  2171. // Check that the field is active again after all modules have been
  2172. // enabled.
  2173. $field = field_read_field($field_name);
  2174. $this->assertTrue($field_definition <= $field, t('The field was was marked active.'));
  2175. }
  2176. }
  2177. class FieldInstanceCrudTestCase extends FieldTestCase {
  2178. protected $field;
  2179. public static function getInfo() {
  2180. return array(
  2181. 'name' => 'Field instance CRUD tests',
  2182. 'description' => 'Create field entities by attaching fields to entities.',
  2183. 'group' => 'Field API',
  2184. );
  2185. }
  2186. function setUp() {
  2187. parent::setUp('field_test');
  2188. $this->field = array(
  2189. 'field_name' => drupal_strtolower($this->randomName()),
  2190. 'type' => 'test_field',
  2191. );
  2192. field_create_field($this->field);
  2193. $this->instance_definition = array(
  2194. 'field_name' => $this->field['field_name'],
  2195. 'entity_type' => 'test_entity',
  2196. 'bundle' => 'test_bundle',
  2197. );
  2198. }
  2199. // TODO : test creation with
  2200. // - a full fledged $instance structure, check that all the values are there
  2201. // - a minimal $instance structure, check all default values are set
  2202. // defer actual $instance comparison to a helper function, used for the two cases above,
  2203. // and for testUpdateFieldInstance
  2204. /**
  2205. * Test the creation of a field instance.
  2206. */
  2207. function testCreateFieldInstance() {
  2208. field_create_instance($this->instance_definition);
  2209. // Read the raw record from the {field_config_instance} table.
  2210. $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']));
  2211. $record = $result->fetchAssoc();
  2212. $record['data'] = unserialize($record['data']);
  2213. $field_type = field_info_field_types($this->field['type']);
  2214. $widget_type = field_info_widget_types($field_type['default_widget']);
  2215. $formatter_type = field_info_formatter_types($field_type['default_formatter']);
  2216. // Check that default values are set.
  2217. $this->assertIdentical($record['data']['required'], FALSE, t('Required defaults to false.'));
  2218. $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], t('Label defaults to field name.'));
  2219. $this->assertIdentical($record['data']['description'], '', t('Description defaults to empty string.'));
  2220. $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], t('Default widget has been written.'));
  2221. $this->assertTrue(isset($record['data']['display']['default']), t('Display for "full" view_mode has been written.'));
  2222. $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], t('Default formatter for "full" view_mode has been written.'));
  2223. // Check that default settings are set.
  2224. $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , t('Default instance settings have been written.'));
  2225. $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , t('Default widget settings have been written.'));
  2226. $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], t('Default formatter settings for "full" view_mode have been written.'));
  2227. // Guarantee that the field/bundle combination is unique.
  2228. try {
  2229. field_create_instance($this->instance_definition);
  2230. $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
  2231. }
  2232. catch (FieldException $e) {
  2233. $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
  2234. }
  2235. // Check that the specified field exists.
  2236. try {
  2237. $this->instance_definition['field_name'] = $this->randomName();
  2238. field_create_instance($this->instance_definition);
  2239. $this->fail(t('Cannot create an instance of a non-existing field.'));
  2240. }
  2241. catch (FieldException $e) {
  2242. $this->pass(t('Cannot create an instance of a non-existing field.'));
  2243. }
  2244. // Create a field restricted to a specific entity type.
  2245. $field_restricted = array(
  2246. 'field_name' => drupal_strtolower($this->randomName()),
  2247. 'type' => 'test_field',
  2248. 'entity_types' => array('test_cacheable_entity'),
  2249. );
  2250. field_create_field($field_restricted);
  2251. // Check that an instance can be added to an entity type allowed
  2252. // by the field.
  2253. try {
  2254. $instance = $this->instance_definition;
  2255. $instance['field_name'] = $field_restricted['field_name'];
  2256. $instance['entity_type'] = 'test_cacheable_entity';
  2257. field_create_instance($instance);
  2258. $this->pass(t('Can create an instance on an entity type allowed by the field.'));
  2259. }
  2260. catch (FieldException $e) {
  2261. $this->fail(t('Can create an instance on an entity type allowed by the field.'));
  2262. }
  2263. // Check that an instance cannot be added to an entity type
  2264. // forbidden by the field.
  2265. try {
  2266. $instance = $this->instance_definition;
  2267. $instance['field_name'] = $field_restricted['field_name'];
  2268. field_create_instance($instance);
  2269. $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
  2270. }
  2271. catch (FieldException $e) {
  2272. $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
  2273. }
  2274. // TODO: test other failures.
  2275. }
  2276. /**
  2277. * Test reading back an instance definition.
  2278. */
  2279. function testReadFieldInstance() {
  2280. field_create_instance($this->instance_definition);
  2281. // Read the instance back.
  2282. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2283. $this->assertTrue($this->instance_definition < $instance, t('The field was properly read.'));
  2284. }
  2285. /**
  2286. * Test the update of a field instance.
  2287. */
  2288. function testUpdateFieldInstance() {
  2289. field_create_instance($this->instance_definition);
  2290. $field_type = field_info_field_types($this->field['type']);
  2291. // Check that basic changes are saved.
  2292. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2293. $instance['required'] = !$instance['required'];
  2294. $instance['label'] = $this->randomName();
  2295. $instance['description'] = $this->randomName();
  2296. $instance['settings']['test_instance_setting'] = $this->randomName();
  2297. $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
  2298. $instance['widget']['weight']++;
  2299. $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
  2300. $instance['display']['default']['weight']++;
  2301. field_update_instance($instance);
  2302. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2303. $this->assertEqual($instance['required'], $instance_new['required'], t('"required" change is saved'));
  2304. $this->assertEqual($instance['label'], $instance_new['label'], t('"label" change is saved'));
  2305. $this->assertEqual($instance['description'], $instance_new['description'], t('"description" change is saved'));
  2306. $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], t('Widget setting change is saved'));
  2307. $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], t('Widget weight change is saved'));
  2308. $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], t('Formatter setting change is saved'));
  2309. $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], t('Widget weight change is saved'));
  2310. // Check that changing widget and formatter types updates the default settings.
  2311. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2312. $instance['widget']['type'] = 'test_field_widget_multiple';
  2313. $instance['display']['default']['type'] = 'field_test_multiple';
  2314. field_update_instance($instance);
  2315. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2316. $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , t('Widget type change is saved.'));
  2317. $settings = field_info_widget_settings($instance_new['widget']['type']);
  2318. $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , t('Widget type change updates default settings.'));
  2319. $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , t('Formatter type change is saved.'));
  2320. $info = field_info_formatter_types($instance_new['display']['default']['type']);
  2321. $settings = $info['settings'];
  2322. $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , t('Changing formatter type updates default settings.'));
  2323. // Check that adding a new view mode is saved and gets default settings.
  2324. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2325. $instance['display']['teaser'] = array();
  2326. field_update_instance($instance);
  2327. $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2328. $this->assertTrue(isset($instance_new['display']['teaser']), t('Display for the new view_mode has been written.'));
  2329. $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], t('Default formatter for the new view_mode has been written.'));
  2330. $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
  2331. $settings = $info['settings'];
  2332. $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , t('Default formatter settings for the new view_mode have been written.'));
  2333. // TODO: test failures.
  2334. }
  2335. /**
  2336. * Test the deletion of a field instance.
  2337. */
  2338. function testDeleteFieldInstance() {
  2339. // TODO: Test deletion of the data stored in the field also.
  2340. // Need to check that data for a 'deleted' field / instance doesn't get loaded
  2341. // Need to check data marked deleted is cleaned on cron (not implemented yet...)
  2342. // Create two instances for the same field so we can test that only one
  2343. // is deleted.
  2344. field_create_instance($this->instance_definition);
  2345. $this->another_instance_definition = $this->instance_definition;
  2346. $this->another_instance_definition['bundle'] .= '_another_bundle';
  2347. $instance = field_create_instance($this->another_instance_definition);
  2348. // Test that the first instance is not deleted, and then delete it.
  2349. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  2350. $this->assertTrue(!empty($instance) && empty($instance['deleted']), t('A new field instance is not marked for deletion.'));
  2351. field_delete_instance($instance);
  2352. // Make sure the instance is marked as deleted when the instance is
  2353. // specifically loaded.
  2354. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
  2355. $this->assertTrue(!empty($instance['deleted']), t('A deleted field instance is marked for deletion.'));
  2356. // Try to load the instance normally and make sure it does not show up.
  2357. $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
  2358. $this->assertTrue(empty($instance), t('A deleted field instance is not loaded by default.'));
  2359. // Make sure the other field instance is not deleted.
  2360. $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
  2361. $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), t('A non-deleted field instance is not marked for deletion.'));
  2362. // Make sure the field is deleted when its last instance is deleted.
  2363. field_delete_instance($another_instance);
  2364. $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
  2365. $this->assertTrue(!empty($field['deleted']), t('A deleted field is marked for deletion after all its instances have been marked for deletion.'));
  2366. }
  2367. }
  2368. /**
  2369. * Unit test class for the multilanguage fields logic.
  2370. *
  2371. * The following tests will check the multilanguage logic of _field_invoke() and
  2372. * that only the correct values are returned by field_available_languages().
  2373. */
  2374. class FieldTranslationsTestCase extends FieldTestCase {
  2375. public static function getInfo() {
  2376. return array(
  2377. 'name' => 'Field translations tests',
  2378. 'description' => 'Test multilanguage fields logic.',
  2379. 'group' => 'Field API',
  2380. );
  2381. }
  2382. function setUp() {
  2383. parent::setUp('locale', 'field_test');
  2384. $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
  2385. $this->entity_type = 'test_entity';
  2386. $field = array(
  2387. 'field_name' => $this->field_name,
  2388. 'type' => 'test_field',
  2389. 'cardinality' => 4,
  2390. 'translatable' => TRUE,
  2391. );
  2392. field_create_field($field);
  2393. $this->field = field_read_field($this->field_name);
  2394. $instance = array(
  2395. 'field_name' => $this->field_name,
  2396. 'entity_type' => $this->entity_type,
  2397. 'bundle' => 'test_bundle',
  2398. );
  2399. field_create_instance($instance);
  2400. $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');
  2401. require_once DRUPAL_ROOT . '/includes/locale.inc';
  2402. for ($i = 0; $i < 3; ++$i) {
  2403. locale_add_language('l' . $i, $this->randomString(), $this->randomString());
  2404. }
  2405. }
  2406. /**
  2407. * Ensures that only valid values are returned by field_available_languages().
  2408. */
  2409. function testFieldAvailableLanguages() {
  2410. // Test 'translatable' fieldable info.
  2411. field_test_entity_info_translatable('test_entity', FALSE);
  2412. $field = $this->field;
  2413. $field['field_name'] .= '_untranslatable';
  2414. // Enable field translations for the entity.
  2415. field_test_entity_info_translatable('test_entity', TRUE);
  2416. // Test hook_field_languages() invocation on a translatable field.
  2417. variable_set('field_test_field_available_languages_alter', TRUE);
  2418. $enabled_languages = field_content_languages();
  2419. $available_languages = field_available_languages($this->entity_type, $this->field);
  2420. foreach ($available_languages as $delta => $langcode) {
  2421. if ($langcode != 'xx' && $langcode != 'en') {
  2422. $this->assertTrue(in_array($langcode, $enabled_languages), t('%language is an enabled language.', array('%language' => $langcode)));
  2423. }
  2424. }
  2425. $this->assertTrue(in_array('xx', $available_languages), t('%language was made available.', array('%language' => 'xx')));
  2426. $this->assertFalse(in_array('en', $available_languages), t('%language was made unavailable.', array('%language' => 'en')));
  2427. // Test field_available_languages() behavior for untranslatable fields.
  2428. $this->field['translatable'] = FALSE;
  2429. field_update_field($this->field);
  2430. $available_languages = field_available_languages($this->entity_type, $this->field);
  2431. $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, t('For untranslatable fields only LANGUAGE_NONE is available.'));
  2432. }
  2433. /**
  2434. * Test the multilanguage logic of _field_invoke().
  2435. */
  2436. function testFieldInvoke() {
  2437. // Enable field translations for the entity.
  2438. field_test_entity_info_translatable('test_entity', TRUE);
  2439. $entity_type = 'test_entity';
  2440. $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
  2441. // Populate some extra languages to check if _field_invoke() correctly uses
  2442. // the result of field_available_languages().
  2443. $values = array();
  2444. $extra_languages = mt_rand(1, 4);
  2445. $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
  2446. for ($i = 0; $i < $extra_languages; ++$i) {
  2447. $languages[] = $this->randomName(2);
  2448. }
  2449. // For each given language provide some random values.
  2450. foreach ($languages as $langcode) {
  2451. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  2452. $values[$langcode][$delta]['value'] = mt_rand(1, 127);
  2453. }
  2454. }
  2455. $entity->{$this->field_name} = $values;
  2456. $results = _field_invoke('test_op', $entity_type, $entity);
  2457. foreach ($results as $langcode => $result) {
  2458. $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
  2459. // Check whether the parameters passed to _field_invoke() were correctly
  2460. // forwarded to the callback function.
  2461. $this->assertEqual($hash, $result, t('The result for %language is correctly stored.', array('%language' => $langcode)));
  2462. }
  2463. $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed.'));
  2464. }
  2465. /**
  2466. * Test the multilanguage logic of _field_invoke_multiple().
  2467. */
  2468. function testFieldInvokeMultiple() {
  2469. // Enable field translations for the entity.
  2470. field_test_entity_info_translatable('test_entity', TRUE);
  2471. $values = array();
  2472. $options = array();
  2473. $entities = array();
  2474. $entity_type = 'test_entity';
  2475. $entity_count = 5;
  2476. $available_languages = field_available_languages($this->entity_type, $this->field);
  2477. for ($id = 1; $id <= $entity_count; ++$id) {
  2478. $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
  2479. $languages = $available_languages;
  2480. // Populate some extra languages to check whether _field_invoke()
  2481. // correctly uses the result of field_available_languages().
  2482. $extra_languages = mt_rand(1, 4);
  2483. for ($i = 0; $i < $extra_languages; ++$i) {
  2484. $languages[] = $this->randomName(2);
  2485. }
  2486. // For each given language provide some random values.
  2487. $language_count = count($languages);
  2488. for ($i = 0; $i < $language_count; ++$i) {
  2489. $langcode = $languages[$i];
  2490. // Avoid to populate at least one field translation to check that
  2491. // per-entity language suggestions work even when available field values
  2492. // are different for each language.
  2493. if ($i !== $id) {
  2494. for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
  2495. $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
  2496. }
  2497. }
  2498. // Ensure that a language for which there is no field translation is
  2499. // used as display language to prepare per-entity language suggestions.
  2500. elseif (!isset($display_language)) {
  2501. $display_language = $langcode;
  2502. }
  2503. }
  2504. $entity->{$this->field_name} = $values[$id];
  2505. $entities[$id] = $entity;
  2506. // Store per-entity language suggestions.
  2507. $options['language'][$id] = field_language($entity_type, $entity, NULL, $display_language);
  2508. }
  2509. $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
  2510. foreach ($grouped_results as $id => $results) {
  2511. foreach ($results as $langcode => $result) {
  2512. if (isset($values[$id][$langcode])) {
  2513. $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
  2514. // Check whether the parameters passed to _field_invoke_multiple()
  2515. // were correctly forwarded to the callback function.
  2516. $this->assertEqual($hash, $result, t('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
  2517. }
  2518. }
  2519. $this->assertEqual(count($results), count($available_languages), t('No unavailable language has been processed for entity %id.', array('%id' => $id)));
  2520. }
  2521. $null = NULL;
  2522. $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities, $null, $null, $options);
  2523. foreach ($grouped_results as $id => $results) {
  2524. foreach ($results as $langcode => $result) {
  2525. $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)));
  2526. }
  2527. }
  2528. }
  2529. /**
  2530. * Test translatable fields storage/retrieval.
  2531. */
  2532. function testTranslatableFieldSaveLoad() {
  2533. // Enable field translations for nodes.
  2534. field_test_entity_info_translatable('node', TRUE);
  2535. $entity_info = entity_get_info('node');
  2536. $this->assertTrue(count($entity_info['translation']), t('Nodes are translatable.'));
  2537. // Prepare the field translations.
  2538. field_test_entity_info_translatable('test_entity', TRUE);
  2539. $eid = $evid = 1;
  2540. $entity_type = 'test_entity';
  2541. $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
  2542. $field_translations = array();
  2543. $available_languages = field_available_languages($entity_type, $this->field);
  2544. $this->assertTrue(count($available_languages) > 1, t('Field is translatable.'));
  2545. foreach ($available_languages as $langcode) {
  2546. $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
  2547. }
  2548. // Save and reload the field translations.
  2549. $entity->{$this->field_name} = $field_translations;
  2550. field_attach_insert($entity_type, $entity);
  2551. unset($entity->{$this->field_name});
  2552. field_attach_load($entity_type, array($eid => $entity));
  2553. // Check if the correct values were saved/loaded.
  2554. foreach ($field_translations as $langcode => $items) {
  2555. $result = TRUE;
  2556. foreach ($items as $delta => $item) {
  2557. $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
  2558. }
  2559. $this->assertTrue($result, t('%language translation correctly handled.', array('%language' => $langcode)));
  2560. }
  2561. }
  2562. /**
  2563. * Tests display language logic for translatable fields.
  2564. */
  2565. function testFieldDisplayLanguage() {
  2566. $field_name = drupal_strtolower($this->randomName() . '_field_name');
  2567. $entity_type = 'test_entity';
  2568. // We need an additional field here to properly test display language
  2569. // suggestions.
  2570. $field = array(
  2571. 'field_name' => $field_name,
  2572. 'type' => 'test_field',
  2573. 'cardinality' => 2,
  2574. 'translatable' => TRUE,
  2575. );
  2576. field_create_field($field);
  2577. $instance = array(
  2578. 'field_name' => $field['field_name'],
  2579. 'entity_type' => $entity_type,
  2580. 'bundle' => 'test_bundle',
  2581. );
  2582. field_create_instance($instance);
  2583. $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
  2584. $instances = field_info_instances($entity_type, $this->instance['bundle']);
  2585. $enabled_languages = field_content_languages();
  2586. $languages = array();
  2587. // Generate field translations for languages different from the first
  2588. // enabled.
  2589. foreach ($instances as $instance) {
  2590. $field_name = $instance['field_name'];
  2591. $field = field_info_field($field_name);
  2592. do {
  2593. // Index 0 is reserved for the requested language, this way we ensure
  2594. // that no field is actually populated with it.
  2595. $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
  2596. }
  2597. while (isset($languages[$langcode]));
  2598. $languages[$langcode] = TRUE;
  2599. $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
  2600. }
  2601. // Test multiple-fields display languages for untranslatable entities.
  2602. field_test_entity_info_translatable($entity_type, FALSE);
  2603. drupal_static_reset('field_language');
  2604. $requested_language = $enabled_languages[0];
  2605. $display_language = field_language($entity_type, $entity, NULL, $requested_language);
  2606. foreach ($instances as $instance) {
  2607. $field_name = $instance['field_name'];
  2608. $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)));
  2609. }
  2610. // Test multiple-fields display languages for translatable entities.
  2611. field_test_entity_info_translatable($entity_type, TRUE);
  2612. drupal_static_reset('field_language');
  2613. $display_language = field_language($entity_type, $entity, NULL, $requested_language);
  2614. foreach ($instances as $instance) {
  2615. $field_name = $instance['field_name'];
  2616. $langcode = $display_language[$field_name];
  2617. // As the requested language was not assinged to any field, if the
  2618. // returned language is defined for the current field, core fallback rules
  2619. // were successfully applied.
  2620. $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)));
  2621. }
  2622. // Test single-field display language.
  2623. drupal_static_reset('field_language');
  2624. $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
  2625. $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)));
  2626. // Test field_language() basic behavior without language fallback.
  2627. variable_set('field_test_language_fallback', FALSE);
  2628. $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
  2629. drupal_static_reset('field_language');
  2630. $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
  2631. $this->assertEqual($display_language, $requested_language, t('Display language behave correctly when language fallback is disabled'));
  2632. }
  2633. /**
  2634. * Tests field translations when creating a new revision.
  2635. */
  2636. function testFieldFormTranslationRevisions() {
  2637. $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
  2638. $this->drupalLogin($web_user);
  2639. // Prepare the field translations.
  2640. field_test_entity_info_translatable($this->entity_type, TRUE);
  2641. $eid = 1;
  2642. $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
  2643. $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
  2644. unset($available_languages[LANGUAGE_NONE]);
  2645. $field_name = $this->field['field_name'];
  2646. // Store the field translations.
  2647. $entity->is_new = TRUE;
  2648. foreach ($available_languages as $langcode => $value) {
  2649. $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
  2650. }
  2651. field_test_entity_save($entity);
  2652. // Create a new revision.
  2653. $langcode = field_valid_language(NULL);
  2654. $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
  2655. $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));
  2656. // Check translation revisions.
  2657. $this->checkTranslationRevisions($eid, $eid, $available_languages);
  2658. $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
  2659. }
  2660. /**
  2661. * Check if the field translation attached to the entity revision identified
  2662. * by the passed arguments were correctly stored.
  2663. */
  2664. private function checkTranslationRevisions($eid, $evid, $available_languages) {
  2665. $field_name = $this->field['field_name'];
  2666. $entity = field_test_entity_test_load($eid, $evid);
  2667. foreach ($available_languages as $langcode => $value) {
  2668. $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
  2669. $this->assertTrue($passed, t('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
  2670. }
  2671. }
  2672. }
  2673. /**
  2674. * Unit test class for field bulk delete and batch purge functionality.
  2675. */
  2676. class FieldBulkDeleteTestCase extends FieldTestCase {
  2677. protected $field;
  2678. public static function getInfo() {
  2679. return array(
  2680. 'name' => 'Field bulk delete tests',
  2681. 'description' => 'Bulk delete fields and instances, and clean up afterwards.',
  2682. 'group' => 'Field API',
  2683. );
  2684. }
  2685. /**
  2686. * Convenience function for Field API tests.
  2687. *
  2688. * Given an array of potentially fully-populated entities and an
  2689. * optional field name, generate an array of stub entities of the
  2690. * same fieldable type which contains the data for the field name
  2691. * (if given).
  2692. *
  2693. * @param $entity_type
  2694. * The entity type of $entities.
  2695. * @param $entities
  2696. * An array of entities of type $entity_type.
  2697. * @param $field_name
  2698. * Optional; a field name whose data should be copied from
  2699. * $entities into the returned stub entities.
  2700. * @return
  2701. * An array of stub entities corresponding to $entities.
  2702. */
  2703. function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
  2704. $stubs = array();
  2705. foreach ($entities as $id => $entity) {
  2706. $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
  2707. if (isset($field_name)) {
  2708. $stub->{$field_name} = $entity->{$field_name};
  2709. }
  2710. $stubs[$id] = $stub;
  2711. }
  2712. return $stubs;
  2713. }
  2714. /**
  2715. * Tests that the expected hooks have been invoked on the expected entities.
  2716. *
  2717. * @param $expected_hooks
  2718. * An array keyed by hook name, with one entry per expected invocation.
  2719. * Each entry is the value of the "$entity" parameter the hook is expected
  2720. * to have been passed.
  2721. * @param $actual_hooks
  2722. * The array of actual hook invocations recorded by field_test_memorize().
  2723. */
  2724. function checkHooksInvocations($expected_hooks, $actual_hooks) {
  2725. foreach ($expected_hooks as $hook => $invocations) {
  2726. $actual_invocations = $actual_hooks[$hook];
  2727. // Check that the number of invocations is correct.
  2728. $this->assertEqual(count($actual_invocations), count($invocations), "$hook() was called the expected number of times.");
  2729. // Check that the hook was called for each expected argument.
  2730. foreach ($invocations as $argument) {
  2731. $found = FALSE;
  2732. foreach ($actual_invocations as $actual_arguments) {
  2733. if ($actual_arguments[1] == $argument) {
  2734. $found = TRUE;
  2735. break;
  2736. }
  2737. }
  2738. $this->assertTrue($found, "$hook() was called on expected argument");
  2739. }
  2740. }
  2741. }
  2742. function setUp() {
  2743. parent::setUp('field_test');
  2744. $this->fields = array();
  2745. $this->instances = array();
  2746. $this->entities = array();
  2747. $this->entities_by_bundles = array();
  2748. // Create two bundles.
  2749. $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
  2750. foreach ($this->bundles as $name => $desc) {
  2751. field_test_create_bundle($name, $desc);
  2752. }
  2753. // Create two fields.
  2754. $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
  2755. $this->fields[] = field_create_field($field);
  2756. $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
  2757. $this->fields[] = field_create_field($field);
  2758. // For each bundle, create an instance of each field, and 10
  2759. // entities with values for each field.
  2760. $id = 0;
  2761. $this->entity_type = 'test_entity';
  2762. foreach ($this->bundles as $bundle) {
  2763. foreach ($this->fields as $field) {
  2764. $instance = array(
  2765. 'field_name' => $field['field_name'],
  2766. 'entity_type' => $this->entity_type,
  2767. 'bundle' => $bundle,
  2768. 'widget' => array(
  2769. 'type' => 'test_field_widget',
  2770. )
  2771. );
  2772. $this->instances[] = field_create_instance($instance);
  2773. }
  2774. for ($i = 0; $i < 10; $i++) {
  2775. $entity = field_test_create_stub_entity($id, $id, $bundle);
  2776. foreach ($this->fields as $field) {
  2777. $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
  2778. }
  2779. $this->entities[$id] = $entity;
  2780. // Also keep track of the entities per bundle.
  2781. $this->entities_by_bundles[$bundle][$id] = $entity;
  2782. field_attach_insert($this->entity_type, $entity);
  2783. $id++;
  2784. }
  2785. }
  2786. }
  2787. /**
  2788. * Verify that deleting an instance leaves the field data items in
  2789. * the database and that the appropriate Field API functions can
  2790. * operate on the deleted data and instance.
  2791. *
  2792. * This tests how EntityFieldQuery interacts with
  2793. * field_delete_instance() and could be moved to FieldCrudTestCase,
  2794. * but depends on this class's setUp().
  2795. */
  2796. function testDeleteFieldInstance() {
  2797. $bundle = reset($this->bundles);
  2798. $field = reset($this->fields);
  2799. // There are 10 entities of this bundle.
  2800. $query = new EntityFieldQuery();
  2801. $found = $query
  2802. ->fieldCondition($field)
  2803. ->entityCondition('bundle', $bundle)
  2804. ->execute();
  2805. $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');
  2806. // Delete the instance.
  2807. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2808. field_delete_instance($instance);
  2809. // The instance still exists, deleted.
  2810. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2811. $this->assertEqual(count($instances), 1, 'There is one deleted instance');
  2812. $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');
  2813. // There are 0 entities of this bundle with non-deleted data.
  2814. $query = new EntityFieldQuery();
  2815. $found = $query
  2816. ->fieldCondition($field)
  2817. ->entityCondition('bundle', $bundle)
  2818. ->execute();
  2819. $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');
  2820. // There are 10 entities of this bundle when deleted fields are allowed, and
  2821. // their values are correct.
  2822. $query = new EntityFieldQuery();
  2823. $found = $query
  2824. ->fieldCondition($field)
  2825. ->entityCondition('bundle', $bundle)
  2826. ->deleted(TRUE)
  2827. ->execute();
  2828. field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
  2829. $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
  2830. foreach ($found['test_entity'] as $id => $entity) {
  2831. $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
  2832. }
  2833. }
  2834. /**
  2835. * Verify that field data items and instances are purged when an
  2836. * instance is deleted.
  2837. */
  2838. function testPurgeInstance() {
  2839. // Start recording hook invocations.
  2840. field_test_memorize();
  2841. $bundle = reset($this->bundles);
  2842. $field = reset($this->fields);
  2843. // Delete the instance.
  2844. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2845. field_delete_instance($instance);
  2846. // No field hooks were called.
  2847. $mem = field_test_memorize();
  2848. $this->assertEqual(count($mem), 0, 'No field hooks were called');
  2849. $batch_size = 2;
  2850. for ($count = 8; $count >= 0; $count -= $batch_size) {
  2851. // Purge two entities.
  2852. field_purge_batch($batch_size);
  2853. // There are $count deleted entities left.
  2854. $query = new EntityFieldQuery();
  2855. $found = $query
  2856. ->fieldCondition($field)
  2857. ->entityCondition('bundle', $bundle)
  2858. ->deleted(TRUE)
  2859. ->execute();
  2860. $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
  2861. }
  2862. // Check hooks invocations.
  2863. // - hook_field_load() (multiple hook) should have been called on all
  2864. // entities by pairs of two.
  2865. // - hook_field_delete() should have been called once for each entity in the
  2866. // bundle.
  2867. $actual_hooks = field_test_memorize();
  2868. $hooks = array();
  2869. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2870. foreach (array_chunk($stubs, $batch_size, TRUE) as $chunk) {
  2871. $hooks['field_test_field_load'][] = $chunk;
  2872. }
  2873. foreach ($stubs as $stub) {
  2874. $hooks['field_test_field_delete'][] = $stub;
  2875. }
  2876. $this->checkHooksInvocations($hooks, $actual_hooks);
  2877. // The instance still exists, deleted.
  2878. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2879. $this->assertEqual(count($instances), 1, 'There is one deleted instance');
  2880. // Purge the instance.
  2881. field_purge_batch($batch_size);
  2882. // The instance is gone.
  2883. $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
  2884. $this->assertEqual(count($instances), 0, 'The instance is gone');
  2885. // The field still exists, not deleted, because it has a second instance.
  2886. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
  2887. $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
  2888. }
  2889. /**
  2890. * Verify that fields are preserved and purged correctly as multiple
  2891. * instances are deleted and purged.
  2892. */
  2893. function testPurgeField() {
  2894. // Start recording hook invocations.
  2895. field_test_memorize();
  2896. $field = reset($this->fields);
  2897. // Delete the first instance.
  2898. $bundle = reset($this->bundles);
  2899. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2900. field_delete_instance($instance);
  2901. // Assert that hook_field_delete() was not called yet.
  2902. $mem = field_test_memorize();
  2903. $this->assertEqual(count($mem), 0, 'No field hooks were called.');
  2904. // Purge the data.
  2905. field_purge_batch(10);
  2906. // Check hooks invocations.
  2907. // - hook_field_load() (multiple hook) should have been called once, for all
  2908. // entities in the bundle.
  2909. // - hook_field_delete() should have been called once for each entity in the
  2910. // bundle.
  2911. $actual_hooks = field_test_memorize();
  2912. $hooks = array();
  2913. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2914. $hooks['field_test_field_load'][] = $stubs;
  2915. foreach ($stubs as $stub) {
  2916. $hooks['field_test_field_delete'][] = $stub;
  2917. }
  2918. $this->checkHooksInvocations($hooks, $actual_hooks);
  2919. // Purge again to purge the instance.
  2920. field_purge_batch(0);
  2921. // The field still exists, not deleted.
  2922. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
  2923. $this->assertTrue(isset($fields[$field['id']]) && !$fields[$field['id']]['deleted'], 'The field exists and is not deleted');
  2924. // Delete the second instance.
  2925. $bundle = next($this->bundles);
  2926. $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
  2927. field_delete_instance($instance);
  2928. // Assert that hook_field_delete() was not called yet.
  2929. $mem = field_test_memorize();
  2930. $this->assertEqual(count($mem), 0, 'No field hooks were called.');
  2931. // Purge the data.
  2932. field_purge_batch(10);
  2933. // Check hooks invocations (same as above, for the 2nd bundle).
  2934. $actual_hooks = field_test_memorize();
  2935. $hooks = array();
  2936. $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
  2937. $hooks['field_test_field_load'][] = $stubs;
  2938. foreach ($stubs as $stub) {
  2939. $hooks['field_test_field_delete'][] = $stub;
  2940. }
  2941. $this->checkHooksInvocations($hooks, $actual_hooks);
  2942. // The field still exists, deleted.
  2943. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
  2944. $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');
  2945. // Purge again to purge the instance and the field.
  2946. field_purge_batch(0);
  2947. // The field is gone.
  2948. $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
  2949. $this->assertEqual(count($fields), 0, 'The field is purged.');
  2950. }
  2951. }
  2952. /**
  2953. * Tests entity properties.
  2954. */
  2955. class EntityPropertiesTestCase extends FieldTestCase {
  2956. public static function getInfo() {
  2957. return array(
  2958. 'name' => 'Entity properties',
  2959. 'description' => 'Tests entity properties.',
  2960. 'group' => 'Entity API',
  2961. );
  2962. }
  2963. function setUp() {
  2964. parent::setUp('field_test');
  2965. }
  2966. /**
  2967. * Tests label key and label callback of an entity.
  2968. */
  2969. function testEntityLabel() {
  2970. $entity_types = array(
  2971. 'test_entity_no_label',
  2972. 'test_entity_label',
  2973. 'test_entity_label_callback',
  2974. );
  2975. $entity = field_test_create_stub_entity();
  2976. foreach ($entity_types as $entity_type) {
  2977. $label = entity_label($entity_type, $entity);
  2978. switch ($entity_type) {
  2979. case 'test_entity_no_label':
  2980. $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
  2981. break;
  2982. case 'test_entity_label':
  2983. $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
  2984. break;
  2985. case 'test_entity_label_callback':
  2986. $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
  2987. break;
  2988. }
  2989. }
  2990. }
  2991. }