field.test 162 KB

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