field.test 164 KB

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