field.test 168 KB

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