field.test 164 KB

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