12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770 |
- <?php
- /**
- * @file
- * Tests for field.module.
- */
- /**
- * Parent class for Field API tests.
- */
- class FieldTestCase extends DrupalWebTestCase {
- var $default_storage = 'field_sql_storage';
- /**
- * Set the default field storage backend for fields created during tests.
- */
- function setUp() {
- // Since this is a base class for many test cases, support the same
- // flexibility that DrupalWebTestCase::setUp() has for the modules to be
- // passed in as either an array or a variable number of string arguments.
- $modules = func_get_args();
- if (isset($modules[0]) && is_array($modules[0])) {
- $modules = $modules[0];
- }
- parent::setUp($modules);
- // Set default storage backend.
- variable_set('field_storage_default', $this->default_storage);
- }
- /**
- * Generate random values for a field_test field.
- *
- * @param $cardinality
- * Number of values to generate.
- * @return
- * An array of random values, in the format expected for field values.
- */
- function _generateTestFieldValues($cardinality) {
- $values = array();
- for ($i = 0; $i < $cardinality; $i++) {
- // field_test fields treat 0 as 'empty value'.
- $values[$i]['value'] = mt_rand(1, 127);
- }
- return $values;
- }
- /**
- * Assert that a field has the expected values in an entity.
- *
- * This function only checks a single column in the field values.
- *
- * @param $entity
- * The entity to test.
- * @param $field_name
- * The name of the field to test
- * @param $langcode
- * The language code for the values.
- * @param $expected_values
- * The array of expected values.
- * @param $column
- * (Optional) the name of the column to check.
- */
- function assertFieldValues($entity, $field_name, $langcode, $expected_values, $column = 'value') {
- $e = clone $entity;
- field_attach_load('test_entity', array($e->ftid => $e));
- $values = isset($e->{$field_name}[$langcode]) ? $e->{$field_name}[$langcode] : array();
- $this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
- foreach ($expected_values as $key => $value) {
- $this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', array('@value' => $value)));
- }
- }
- }
- class FieldAttachTestCase extends FieldTestCase {
- function setUp() {
- // Since this is a base class for many test cases, support the same
- // flexibility that DrupalWebTestCase::setUp() has for the modules to be
- // passed in as either an array or a variable number of string arguments.
- $modules = func_get_args();
- if (isset($modules[0]) && is_array($modules[0])) {
- $modules = $modules[0];
- }
- if (!in_array('field_test', $modules)) {
- $modules[] = 'field_test';
- }
- parent::setUp($modules);
- $this->createFieldWithInstance();
- }
- /**
- * Create a field and an instance of it.
- *
- * @param string $suffix
- * (optional) A string that should only contain characters that are valid in
- * PHP variable names as well.
- */
- function createFieldWithInstance($suffix = '') {
- $field_name = 'field_name' . $suffix;
- $field = 'field' . $suffix;
- $field_id = 'field_id' . $suffix;
- $instance = 'instance' . $suffix;
- $this->$field_name = drupal_strtolower($this->randomName() . '_field_name' . $suffix);
- $this->$field = array('field_name' => $this->$field_name, 'type' => 'test_field', 'cardinality' => 4);
- $this->$field = field_create_field($this->$field);
- $this->$field_id = $this->{$field}['id'];
- $this->$instance = array(
- 'field_name' => $this->$field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'label' => $this->randomName() . '_label',
- 'description' => $this->randomName() . '_description',
- 'weight' => mt_rand(0, 127),
- 'settings' => array(
- 'test_instance_setting' => $this->randomName(),
- ),
- 'widget' => array(
- 'type' => 'test_field_widget',
- 'label' => 'Test Field',
- 'settings' => array(
- 'test_widget_setting' => $this->randomName(),
- )
- )
- );
- field_create_instance($this->$instance);
- }
- }
- /**
- * Unit test class for storage-related field_attach_* functions.
- *
- * All field_attach_* test work with all field_storage plugins and
- * all hook_field_attach_pre_{load,insert,update}() hooks.
- */
- class FieldAttachStorageTestCase extends FieldAttachTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field attach tests (storage-related)',
- 'description' => 'Test storage-related Field Attach API functions.',
- 'group' => 'Field API',
- );
- }
- /**
- * Check field values insert, update and load.
- *
- * Works independently of the underlying field storage backend. Inserts or
- * updates random field data and then loads and verifies the data.
- */
- function testFieldAttachSaveLoad() {
- // Configure the instance so that we test hook_field_load() (see
- // field_test_field_load() in field_test.module).
- $this->instance['settings']['test_hook_field_load'] = TRUE;
- field_update_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- $entity_type = 'test_entity';
- $values = array();
- // TODO : test empty values filtering and "compression" (store consecutive deltas).
- // Preparation: create three revisions and store them in $revision array.
- for ($revision_id = 0; $revision_id < 3; $revision_id++) {
- $revision[$revision_id] = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
- // Note: we try to insert one extra value.
- $values[$revision_id] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
- $current_revision = $revision_id;
- // If this is the first revision do an insert.
- if (!$revision_id) {
- $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
- field_attach_insert($entity_type, $revision[$revision_id]);
- }
- else {
- // Otherwise do an update.
- $revision[$revision_id]->{$this->field_name}[$langcode] = $values[$revision_id];
- field_attach_update($entity_type, $revision[$revision_id]);
- }
- }
- // Confirm current revision loads the correct data.
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- field_attach_load($entity_type, array(0 => $entity));
- // Number of values per field loaded equals the field cardinality.
- $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], 'Current revision: expected number of values');
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- // The field value loaded matches the one inserted or updated.
- $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)));
- // The value added in hook_field_load() is found.
- $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)));
- }
- // Confirm each revision loads the correct data.
- foreach (array_keys($revision) as $revision_id) {
- $entity = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
- field_attach_load_revision($entity_type, array(0 => $entity));
- // Number of values per field loaded equals the field cardinality.
- $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)));
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- // The field value loaded matches the one inserted or updated.
- $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)));
- // The value added in hook_field_load() is found.
- $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)));
- }
- }
- }
- /**
- * Test the 'multiple' load feature.
- */
- function testFieldAttachLoadMultiple() {
- $entity_type = 'test_entity';
- $langcode = LANGUAGE_NONE;
- // Define 2 bundles.
- $bundles = array(
- 1 => 'test_bundle_1',
- 2 => 'test_bundle_2',
- );
- field_test_create_bundle($bundles[1]);
- field_test_create_bundle($bundles[2]);
- // Define 3 fields:
- // - field_1 is in bundle_1 and bundle_2,
- // - field_2 is in bundle_1,
- // - field_3 is in bundle_2.
- $field_bundles_map = array(
- 1 => array(1, 2),
- 2 => array(1),
- 3 => array(2),
- );
- for ($i = 1; $i <= 3; $i++) {
- $field_names[$i] = 'field_' . $i;
- $field = array('field_name' => $field_names[$i], 'type' => 'test_field');
- $field = field_create_field($field);
- $field_ids[$i] = $field['id'];
- foreach ($field_bundles_map[$i] as $bundle) {
- $instance = array(
- 'field_name' => $field_names[$i],
- 'entity_type' => 'test_entity',
- 'bundle' => $bundles[$bundle],
- 'settings' => array(
- // Configure the instance so that we test hook_field_load()
- // (see field_test_field_load() in field_test.module).
- 'test_hook_field_load' => TRUE,
- ),
- );
- field_create_instance($instance);
- }
- }
- // Create one test entity per bundle, with random values.
- foreach ($bundles as $index => $bundle) {
- $entities[$index] = field_test_create_stub_entity($index, $index, $bundle);
- $entity = clone($entities[$index]);
- $instances = field_info_instances('test_entity', $bundle);
- foreach ($instances as $field_name => $instance) {
- $values[$index][$field_name] = mt_rand(1, 127);
- $entity->$field_name = array($langcode => array(array('value' => $values[$index][$field_name])));
- }
- field_attach_insert($entity_type, $entity);
- }
- // Check that a single load correctly loads field values for both entities.
- field_attach_load($entity_type, $entities);
- foreach ($entities as $index => $entity) {
- $instances = field_info_instances($entity_type, $bundles[$index]);
- foreach ($instances as $field_name => $instance) {
- // The field value loaded matches the one inserted.
- $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], $values[$index][$field_name], format_string('Entity %index: expected value was found.', array('%index' => $index)));
- // The value added in hook_field_load() is found.
- $this->assertEqual($entity->{$field_name}[$langcode][0]['additional_key'], 'additional_value', format_string('Entity %index: extra information was found', array('%index' => $index)));
- }
- }
- // Check that the single-field load option works.
- $entity = field_test_create_stub_entity(1, 1, $bundles[1]);
- field_attach_load($entity_type, array(1 => $entity), FIELD_LOAD_CURRENT, array('field_id' => $field_ids[1]));
- $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)));
- $this->assertEqual($entity->{$field_names[1]}[$langcode][0]['additional_key'], 'additional_value', format_string('Entity %index: extra information was found', array('%index' => 1)));
- $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])));
- $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])));
- }
- /**
- * Test saving and loading fields using different storage backends.
- */
- function testFieldAttachSaveLoadDifferentStorage() {
- $entity_type = 'test_entity';
- $langcode = LANGUAGE_NONE;
- // Create two fields using different storage backends, and their instances.
- $fields = array(
- array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- 'cardinality' => 4,
- 'storage' => array('type' => 'field_sql_storage')
- ),
- array(
- 'field_name' => 'field_2',
- 'type' => 'test_field',
- 'cardinality' => 4,
- 'storage' => array('type' => 'field_test_storage')
- ),
- );
- foreach ($fields as $field) {
- field_create_field($field);
- $instance = array(
- 'field_name' => $field['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance);
- }
- $entity_init = field_test_create_stub_entity();
- // Create entity and insert random values.
- $entity = clone($entity_init);
- $values = array();
- foreach ($fields as $field) {
- $values[$field['field_name']] = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity->{$field['field_name']}[$langcode] = $values[$field['field_name']];
- }
- field_attach_insert($entity_type, $entity);
- // Check that values are loaded as expected.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- foreach ($fields as $field) {
- $this->assertEqual($values[$field['field_name']], $entity->{$field['field_name']}[$langcode], format_string('%storage storage: expected values were found.', array('%storage' => $field['storage']['type'])));
- }
- }
- /**
- * Test storage details alteration.
- *
- * @see field_test_storage_details_alter()
- */
- function testFieldStorageDetailsAlter() {
- $field_name = 'field_test_change_my_details';
- $field = array(
- 'field_name' => $field_name,
- 'type' => 'test_field',
- 'cardinality' => 4,
- 'storage' => array('type' => 'field_test_storage'),
- );
- $field = field_create_field($field);
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance);
- $field = field_info_field($instance['field_name']);
- $instance = field_info_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
- // The storage details are indexed by a storage engine type.
- $this->assertTrue(array_key_exists('drupal_variables', $field['storage']['details']), 'The storage type is Drupal variables.');
- $details = $field['storage']['details']['drupal_variables'];
- // The field_test storage details are indexed by variable name. The details
- // are altered, so moon and mars are correct for this test.
- $this->assertTrue(array_key_exists('moon', $details[FIELD_LOAD_CURRENT]), 'Moon is available in the instance array.');
- $this->assertTrue(array_key_exists('mars', $details[FIELD_LOAD_REVISION]), 'Mars is available in the instance array.');
- // Test current and revision storage details together because the columns
- // are the same.
- foreach ((array) $field['columns'] as $column_name => $attributes) {
- $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]')));
- $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]')));
- }
- }
- /**
- * Tests insert and update with missing or NULL fields.
- */
- function testFieldAttachSaveMissingData() {
- $entity_type = 'test_entity';
- $entity_init = field_test_create_stub_entity();
- $langcode = LANGUAGE_NONE;
- // Insert: Field is missing.
- $entity = clone($entity_init);
- field_attach_insert($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertTrue(empty($entity->{$this->field_name}), 'Insert: missing field results in no value saved');
- // Insert: Field is NULL.
- field_cache_clear();
- $entity = clone($entity_init);
- $entity->{$this->field_name} = NULL;
- field_attach_insert($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertTrue(empty($entity->{$this->field_name}), 'Insert: NULL field results in no value saved');
- // Add some real data.
- field_cache_clear();
- $entity = clone($entity_init);
- $values = $this->_generateTestFieldValues(1);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_insert($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertEqual($entity->{$this->field_name}[$langcode], $values, 'Field data saved');
- // Update: Field is missing. Data should survive.
- field_cache_clear();
- $entity = clone($entity_init);
- field_attach_update($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertEqual($entity->{$this->field_name}[$langcode], $values, 'Update: missing field leaves existing values in place');
- // Update: Field is NULL. Data should be wiped.
- field_cache_clear();
- $entity = clone($entity_init);
- $entity->{$this->field_name} = NULL;
- field_attach_update($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertTrue(empty($entity->{$this->field_name}), 'Update: NULL field removes existing values');
- // Re-add some data.
- field_cache_clear();
- $entity = clone($entity_init);
- $values = $this->_generateTestFieldValues(1);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_update($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertEqual($entity->{$this->field_name}[$langcode], $values, 'Field data saved');
- // Update: Field is empty array. Data should be wiped.
- field_cache_clear();
- $entity = clone($entity_init);
- $entity->{$this->field_name} = array();
- field_attach_update($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertTrue(empty($entity->{$this->field_name}), 'Update: empty array removes existing values');
- }
- /**
- * Test insert with missing or NULL fields, with default value.
- */
- function testFieldAttachSaveMissingDataDefaultValue() {
- // Add a default value function.
- $this->instance['default_value_function'] = 'field_test_default_value';
- field_update_instance($this->instance);
- $entity_type = 'test_entity';
- $entity_init = field_test_create_stub_entity();
- $langcode = LANGUAGE_NONE;
- // Insert: Field is NULL.
- $entity = clone($entity_init);
- $entity->{$this->field_name}[$langcode] = NULL;
- field_attach_insert($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertTrue(empty($entity->{$this->field_name}[$langcode]), 'Insert: NULL field results in no value saved');
- // Insert: Field is missing.
- field_cache_clear();
- $entity = clone($entity_init);
- field_attach_insert($entity_type, $entity);
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $values = field_test_default_value($entity_type, $entity, $this->field, $this->instance);
- $this->assertEqual($entity->{$this->field_name}[$langcode], $values, 'Insert: missing field results in default value saved');
- }
- /**
- * Test field_has_data().
- */
- function testFieldHasData() {
- $entity_type = 'test_entity';
- $langcode = LANGUAGE_NONE;
- $field_name = 'field_1';
- $field = array('field_name' => $field_name, 'type' => 'test_field');
- $field = field_create_field($field);
- $this->assertFalse(field_has_data($field), "No data should be detected.");
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle'
- );
- $instance = field_create_instance($instance);
- $table = _field_sql_storage_tablename($field);
- $revision_table = _field_sql_storage_revision_tablename($field);
- $columns = array('entity_type', 'entity_id', 'revision_id', 'delta', 'language', $field_name . '_value');
- $eid = 0;
- // Insert values into the field revision table.
- $query = db_insert($revision_table)->fields($columns);
- $query->values(array($entity_type, $eid, 0, 0, $langcode, 1));
- $query->execute();
- $this->assertTrue(field_has_data($field), "Revision data only should be detected.");
- $field_name = 'field_2';
- $field = array('field_name' => $field_name, 'type' => 'test_field');
- $field = field_create_field($field);
- $this->assertFalse(field_has_data($field), "No data should be detected.");
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle'
- );
- $instance = field_create_instance($instance);
- $table = _field_sql_storage_tablename($field);
- $revision_table = _field_sql_storage_revision_tablename($field);
- $columns = array('entity_type', 'entity_id', 'revision_id', 'delta', 'language', $field_name . '_value');
- $eid = 1;
- // Insert values into the field table.
- $query = db_insert($table)->fields($columns);
- $query->values(array($entity_type, $eid, 0, 0, $langcode, 1));
- $query->execute();
- $this->assertTrue(field_has_data($field), "Values only in field table should be detected.");
- }
- /**
- * Test field_attach_delete().
- */
- function testFieldAttachDelete() {
- $entity_type = 'test_entity';
- $langcode = LANGUAGE_NONE;
- $rev[0] = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- // Create revision 0
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $rev[0]->{$this->field_name}[$langcode] = $values;
- field_attach_insert($entity_type, $rev[0]);
- // Create revision 1
- $rev[1] = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
- $rev[1]->{$this->field_name}[$langcode] = $values;
- field_attach_update($entity_type, $rev[1]);
- // Create revision 2
- $rev[2] = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
- $rev[2]->{$this->field_name}[$langcode] = $values;
- field_attach_update($entity_type, $rev[2]);
- // Confirm each revision loads
- foreach (array_keys($rev) as $vid) {
- $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
- field_attach_load_revision($entity_type, array(0 => $read));
- $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
- }
- // Delete revision 1, confirm the other two still load.
- field_attach_delete_revision($entity_type, $rev[1]);
- foreach (array(0, 2) as $vid) {
- $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
- field_attach_load_revision($entity_type, array(0 => $read));
- $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
- }
- // Confirm the current revision still loads
- $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
- field_attach_load($entity_type, array(0 => $read));
- $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity current revision has {$this->field['cardinality']} values.");
- // Delete all field data, confirm nothing loads
- field_attach_delete($entity_type, $rev[2]);
- foreach (array(0, 1, 2) as $vid) {
- $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
- field_attach_load_revision($entity_type, array(0 => $read));
- $this->assertIdentical($read->{$this->field_name}, array(), "The test entity revision $vid is deleted.");
- }
- $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
- field_attach_load($entity_type, array(0 => $read));
- $this->assertIdentical($read->{$this->field_name}, array(), 'The test entity current revision is deleted.');
- }
- /**
- * Test field_attach_create_bundle() and field_attach_rename_bundle().
- */
- function testFieldAttachCreateRenameBundle() {
- // Create a new bundle. This has to be initiated by the module so that its
- // hook_entity_info() is consistent.
- $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
- field_test_create_bundle($new_bundle);
- // Add an instance to that bundle.
- $this->instance['bundle'] = $new_bundle;
- field_create_instance($this->instance);
- // Save an entity with data in the field.
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity->{$this->field_name}[$langcode] = $values;
- $entity_type = 'test_entity';
- field_attach_insert($entity_type, $entity);
- // Verify the field data is present on load.
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- field_attach_load($entity_type, array(0 => $entity));
- $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Data is retrieved for the new bundle");
- // Rename the bundle. This has to be initiated by the module so that its
- // hook_entity_info() is consistent.
- $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
- field_test_rename_bundle($this->instance['bundle'], $new_bundle);
- // Check that the instance definition has been updated.
- $this->instance = field_info_instance($entity_type, $this->field_name, $new_bundle);
- $this->assertIdentical($this->instance['bundle'], $new_bundle, "Bundle name has been updated in the instance.");
- // Verify the field data is present on load.
- $entity = field_test_create_stub_entity(0, 0, $new_bundle);
- field_attach_load($entity_type, array(0 => $entity));
- $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Bundle name has been updated in the field storage");
- }
- /**
- * Test field_attach_delete_bundle().
- */
- function testFieldAttachDeleteBundle() {
- // Create a new bundle. This has to be initiated by the module so that its
- // hook_entity_info() is consistent.
- $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
- field_test_create_bundle($new_bundle);
- // Add an instance to that bundle.
- $this->instance['bundle'] = $new_bundle;
- field_create_instance($this->instance);
- // Create a second field for the test bundle
- $field_name = drupal_strtolower($this->randomName() . '_field_name');
- $field = array('field_name' => $field_name, 'type' => 'test_field', 'cardinality' => 1);
- field_create_field($field);
- $instance = array(
- 'field_name' => $field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => $this->instance['bundle'],
- 'label' => $this->randomName() . '_label',
- 'description' => $this->randomName() . '_description',
- 'weight' => mt_rand(0, 127),
- // test_field has no instance settings
- 'widget' => array(
- 'type' => 'test_field_widget',
- 'settings' => array(
- 'size' => mt_rand(0, 255))));
- field_create_instance($instance);
- // Save an entity with data for both fields
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity->{$this->field_name}[$langcode] = $values;
- $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues(1);
- field_attach_insert('test_entity', $entity);
- // Verify the fields are present on load
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- field_attach_load('test_entity', array(0 => $entity));
- $this->assertEqual(count($entity->{$this->field_name}[$langcode]), 4, 'First field got loaded');
- $this->assertEqual(count($entity->{$field_name}[$langcode]), 1, 'Second field got loaded');
- // Delete the bundle. This has to be initiated by the module so that its
- // hook_entity_info() is consistent.
- field_test_delete_bundle($this->instance['bundle']);
- // Verify no data gets loaded
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- field_attach_load('test_entity', array(0 => $entity));
- $this->assertFalse(isset($entity->{$this->field_name}[$langcode]), 'No data for first field');
- $this->assertFalse(isset($entity->{$field_name}[$langcode]), 'No data for second field');
- // Verify that the instances are gone
- $this->assertFalse(field_read_instance('test_entity', $this->field_name, $this->instance['bundle']), "First field is deleted");
- $this->assertFalse(field_read_instance('test_entity', $field_name, $instance['bundle']), "Second field is deleted");
- }
- }
- /**
- * Unit test class for non-storage related field_attach_* functions.
- */
- class FieldAttachOtherTestCase extends FieldAttachTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field attach tests (other)',
- 'description' => 'Test other Field Attach API functions.',
- 'group' => 'Field API',
- );
- }
- /**
- * Test field_attach_view() and field_attach_prepare_view().
- */
- function testFieldAttachView() {
- $this->createFieldWithInstance('_2');
- $entity_type = 'test_entity';
- $entity_init = field_test_create_stub_entity();
- $langcode = LANGUAGE_NONE;
- $options = array('field_name' => $this->field_name_2);
- // Populate values to be displayed.
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity_init->{$this->field_name}[$langcode] = $values;
- $values_2 = $this->_generateTestFieldValues($this->field_2['cardinality']);
- $entity_init->{$this->field_name_2}[$langcode] = $values_2;
- // Simple formatter, label displayed.
- $entity = clone($entity_init);
- $formatter_setting = $this->randomName();
- $this->instance['display'] = array(
- 'full' => array(
- 'label' => 'above',
- 'type' => 'field_test_default',
- 'settings' => array(
- 'test_formatter_setting' => $formatter_setting,
- )
- ),
- );
- field_update_instance($this->instance);
- $formatter_setting_2 = $this->randomName();
- $this->instance_2['display'] = array(
- 'full' => array(
- 'label' => 'above',
- 'type' => 'field_test_default',
- 'settings' => array(
- 'test_formatter_setting' => $formatter_setting_2,
- )
- ),
- );
- field_update_instance($this->instance_2);
- // View all fields.
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
- $entity->content = field_attach_view($entity_type, $entity, 'full');
- $output = drupal_render($entity->content);
- $this->content = $output;
- $this->assertRaw($this->instance['label'], "First field's label is displayed.");
- foreach ($values as $delta => $value) {
- $this->content = $output;
- $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
- }
- $this->assertRaw($this->instance_2['label'], "Second field's label is displayed.");
- foreach ($values_2 as $delta => $value) {
- $this->content = $output;
- $this->assertRaw("$formatter_setting_2|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
- }
- // View single field (the second field).
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full', $langcode, $options);
- $entity->content = field_attach_view($entity_type, $entity, 'full', $langcode, $options);
- $output = drupal_render($entity->content);
- $this->content = $output;
- $this->assertNoRaw($this->instance['label'], "First field's label is not displayed.");
- foreach ($values as $delta => $value) {
- $this->content = $output;
- $this->assertNoRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
- }
- $this->assertRaw($this->instance_2['label'], "Second field's label is displayed.");
- foreach ($values_2 as $delta => $value) {
- $this->content = $output;
- $this->assertRaw("$formatter_setting_2|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
- }
- // Label hidden.
- $entity = clone($entity_init);
- $this->instance['display']['full']['label'] = 'hidden';
- field_update_instance($this->instance);
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
- $entity->content = field_attach_view($entity_type, $entity, 'full');
- $output = drupal_render($entity->content);
- $this->content = $output;
- $this->assertNoRaw($this->instance['label'], "Hidden label: label is not displayed.");
- // Field hidden.
- $entity = clone($entity_init);
- $this->instance['display'] = array(
- 'full' => array(
- 'label' => 'above',
- 'type' => 'hidden',
- ),
- );
- field_update_instance($this->instance);
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
- $entity->content = field_attach_view($entity_type, $entity, 'full');
- $output = drupal_render($entity->content);
- $this->content = $output;
- $this->assertNoRaw($this->instance['label'], "Hidden field: label is not displayed.");
- foreach ($values as $delta => $value) {
- $this->assertNoRaw("$formatter_setting|{$value['value']}", "Hidden field: value $delta is not displayed.");
- }
- // Multiple formatter.
- $entity = clone($entity_init);
- $formatter_setting = $this->randomName();
- $this->instance['display'] = array(
- 'full' => array(
- 'label' => 'above',
- 'type' => 'field_test_multiple',
- 'settings' => array(
- 'test_formatter_setting_multiple' => $formatter_setting,
- )
- ),
- );
- field_update_instance($this->instance);
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
- $entity->content = field_attach_view($entity_type, $entity, 'full');
- $output = drupal_render($entity->content);
- $display = $formatter_setting;
- foreach ($values as $delta => $value) {
- $display .= "|$delta:{$value['value']}";
- }
- $this->content = $output;
- $this->assertRaw($display, "Multiple formatter: all values are displayed, formatter settings are applied.");
- // Test a formatter that uses hook_field_formatter_prepare_view().
- $entity = clone($entity_init);
- $formatter_setting = $this->randomName();
- $this->instance['display'] = array(
- 'full' => array(
- 'label' => 'above',
- 'type' => 'field_test_with_prepare_view',
- 'settings' => array(
- 'test_formatter_setting_additional' => $formatter_setting,
- )
- ),
- );
- field_update_instance($this->instance);
- field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
- $entity->content = field_attach_view($entity_type, $entity, 'full');
- $output = drupal_render($entity->content);
- $this->content = $output;
- foreach ($values as $delta => $value) {
- $this->content = $output;
- $expected = $formatter_setting . '|' . $value['value'] . '|' . ($value['value'] + 1);
- $this->assertRaw($expected, "Value $delta is displayed, formatter settings are applied.");
- }
- // TODO:
- // - check display order with several fields
- // Preprocess template.
- $variables = array();
- field_attach_preprocess($entity_type, $entity, $entity->content, $variables);
- $result = TRUE;
- foreach ($values as $delta => $item) {
- if ($variables[$this->field_name][$delta]['value'] !== $item['value']) {
- $result = FALSE;
- break;
- }
- }
- $this->assertTrue($result, format_string('Variable $@field_name correctly populated.', array('@field_name' => $this->field_name)));
- }
- /**
- * Tests the 'multiple entity' behavior of field_attach_prepare_view().
- */
- function testFieldAttachPrepareViewMultiple() {
- $entity_type = 'test_entity';
- $langcode = LANGUAGE_NONE;
- // Set the instance to be hidden.
- $this->instance['display']['full']['type'] = 'hidden';
- field_update_instance($this->instance);
- // Set up a second instance on another bundle, with a formatter that uses
- // hook_field_formatter_prepare_view().
- field_test_create_bundle('test_bundle_2');
- $formatter_setting = $this->randomName();
- $this->instance2 = $this->instance;
- $this->instance2['bundle'] = 'test_bundle_2';
- $this->instance2['display']['full'] = array(
- 'type' => 'field_test_with_prepare_view',
- 'settings' => array(
- 'test_formatter_setting_additional' => $formatter_setting,
- )
- );
- field_create_instance($this->instance2);
- // Create one entity in each bundle.
- $entity1_init = field_test_create_stub_entity(1, 1, 'test_bundle');
- $values1 = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity1_init->{$this->field_name}[$langcode] = $values1;
- $entity2_init = field_test_create_stub_entity(2, 2, 'test_bundle_2');
- $values2 = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity2_init->{$this->field_name}[$langcode] = $values2;
- // Run prepare_view, and check that the entities come out as expected.
- $entity1 = clone($entity1_init);
- $entity2 = clone($entity2_init);
- field_attach_prepare_view($entity_type, array($entity1->ftid => $entity1, $entity2->ftid => $entity2), 'full');
- $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
- $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
- // Same thing, reversed order.
- $entity1 = clone($entity1_init);
- $entity2 = clone($entity2_init);
- field_attach_prepare_view($entity_type, array($entity2->ftid => $entity2, $entity1->ftid => $entity1), 'full');
- $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
- $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
- }
- /**
- * Test field cache.
- */
- function testFieldAttachCache() {
- // Initialize random values and a test entity.
- $entity_init = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- // Non-cacheable entity type.
- $entity_type = 'test_entity';
- $cid = "field:$entity_type:{$entity_init->ftid}";
- // Check that no initial cache entry is present.
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no initial cache entry');
- // Save, and check that no cache entry is present.
- $entity = clone($entity_init);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_insert($entity_type, $entity);
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no cache entry on insert');
- // Load, and check that no cache entry is present.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no cache entry on load');
- // Cacheable entity type.
- $entity_type = 'test_cacheable_entity';
- $cid = "field:$entity_type:{$entity_init->ftid}";
- $instance = $this->instance;
- $instance['entity_type'] = $entity_type;
- field_create_instance($instance);
- // Check that no initial cache entry is present.
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no initial cache entry');
- // Save, and check that no cache entry is present.
- $entity = clone($entity_init);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_insert($entity_type, $entity);
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on insert');
- // Load a single field, and check that no cache entry is present.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity), FIELD_LOAD_CURRENT, array('field_id' => $this->field_id));
- $cache = cache_get($cid, 'cache_field');
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on loading a single field');
- // Load, and check that a cache entry is present with the expected values.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $cache = cache_get($cid, 'cache_field');
- $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
- // Update with different values, and check that the cache entry is wiped.
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity = clone($entity_init);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_update($entity_type, $entity);
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on update');
- // Load, and check that a cache entry is present with the expected values.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $cache = cache_get($cid, 'cache_field');
- $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
- // Create a new revision, and check that the cache entry is wiped.
- $entity_init = field_test_create_stub_entity(1, 2, $this->instance['bundle']);
- $values = $this->_generateTestFieldValues($this->field['cardinality']);
- $entity = clone($entity_init);
- $entity->{$this->field_name}[$langcode] = $values;
- field_attach_update($entity_type, $entity);
- $cache = cache_get($cid, 'cache_field');
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on new revision creation');
- // Load, and check that a cache entry is present with the expected values.
- $entity = clone($entity_init);
- field_attach_load($entity_type, array($entity->ftid => $entity));
- $cache = cache_get($cid, 'cache_field');
- $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
- // Delete, and check that the cache entry is wiped.
- field_attach_delete($entity_type, $entity);
- $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry after delete');
- }
- /**
- * Test field_attach_validate().
- *
- * Verify that field_attach_validate() invokes the correct
- * hook_field_validate.
- */
- function testFieldAttachValidate() {
- $this->createFieldWithInstance('_2');
- $entity_type = 'test_entity';
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- // Set up all but one values of the first field to generate errors.
- $values = array();
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- $values[$delta]['value'] = -1;
- }
- // Arrange for item 1 not to generate an error
- $values[1]['value'] = 1;
- $entity->{$this->field_name}[$langcode] = $values;
- // Set up all values of the second field to generate errors.
- $values_2 = array();
- for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
- $values_2[$delta]['value'] = -1;
- }
- $entity->{$this->field_name_2}[$langcode] = $values_2;
- // Validate all fields.
- try {
- field_attach_validate($entity_type, $entity);
- }
- catch (FieldValidationException $e) {
- $errors = $e->errors;
- }
- foreach ($values as $delta => $value) {
- if ($value['value'] != 1) {
- $this->assertIdentical($errors[$this->field_name][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on first field's value $delta");
- $this->assertEqual(count($errors[$this->field_name][$langcode][$delta]), 1, "Only one error set on first field's value $delta");
- unset($errors[$this->field_name][$langcode][$delta]);
- }
- else {
- $this->assertFalse(isset($errors[$this->field_name][$langcode][$delta]), "No error set on first field's value $delta");
- }
- }
- foreach ($values_2 as $delta => $value) {
- $this->assertIdentical($errors[$this->field_name_2][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on second field's value $delta");
- $this->assertEqual(count($errors[$this->field_name_2][$langcode][$delta]), 1, "Only one error set on second field's value $delta");
- unset($errors[$this->field_name_2][$langcode][$delta]);
- }
- $this->assertEqual(count($errors[$this->field_name][$langcode]), 0, 'No extraneous errors set for first field');
- $this->assertEqual(count($errors[$this->field_name_2][$langcode]), 0, 'No extraneous errors set for second field');
- // Validate a single field.
- $options = array('field_name' => $this->field_name_2);
- try {
- field_attach_validate($entity_type, $entity, $options);
- }
- catch (FieldValidationException $e) {
- $errors = $e->errors;
- }
- foreach ($values_2 as $delta => $value) {
- $this->assertIdentical($errors[$this->field_name_2][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on second field's value $delta");
- $this->assertEqual(count($errors[$this->field_name_2][$langcode][$delta]), 1, "Only one error set on second field's value $delta");
- unset($errors[$this->field_name_2][$langcode][$delta]);
- }
- $this->assertFalse(isset($errors[$this->field_name]), 'No validation errors are set for the first field, despite it having errors');
- $this->assertEqual(count($errors[$this->field_name_2][$langcode]), 0, 'No extraneous errors set for second field');
- // Check that cardinality is validated.
- $entity->{$this->field_name_2}[$langcode] = $this->_generateTestFieldValues($this->field_2['cardinality'] + 1);
- // When validating all fields.
- try {
- field_attach_validate($entity_type, $entity);
- }
- catch (FieldValidationException $e) {
- $errors = $e->errors;
- }
- $this->assertEqual($errors[$this->field_name_2][$langcode][0][0]['error'], 'field_cardinality', 'Cardinality validation failed.');
- // When validating a single field (the second field).
- try {
- field_attach_validate($entity_type, $entity, $options);
- }
- catch (FieldValidationException $e) {
- $errors = $e->errors;
- }
- $this->assertEqual($errors[$this->field_name_2][$langcode][0][0]['error'], 'field_cardinality', 'Cardinality validation failed.');
- }
- /**
- * Test field_attach_form().
- *
- * This could be much more thorough, but it does verify that the correct
- * widgets show up.
- */
- function testFieldAttachForm() {
- $this->createFieldWithInstance('_2');
- $entity_type = 'test_entity';
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- // When generating form for all fields.
- $form = array();
- $form_state = form_state_defaults();
- field_attach_form($entity_type, $entity, $form, $form_state);
- $this->assertEqual($form[$this->field_name][$langcode]['#title'], $this->instance['label'], "First field's form title is {$this->instance['label']}");
- $this->assertEqual($form[$this->field_name_2][$langcode]['#title'], $this->instance_2['label'], "Second field's form title is {$this->instance_2['label']}");
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- // field_test_widget uses 'textfield'
- $this->assertEqual($form[$this->field_name][$langcode][$delta]['value']['#type'], 'textfield', "First field's form delta $delta widget is textfield");
- }
- for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
- // field_test_widget uses 'textfield'
- $this->assertEqual($form[$this->field_name_2][$langcode][$delta]['value']['#type'], 'textfield', "Second field's form delta $delta widget is textfield");
- }
- // When generating form for a single field (the second field).
- $options = array('field_name' => $this->field_name_2);
- $form = array();
- $form_state = form_state_defaults();
- field_attach_form($entity_type, $entity, $form, $form_state, NULL, $options);
- $this->assertFalse(isset($form[$this->field_name]), 'The first field does not exist in the form');
- $this->assertEqual($form[$this->field_name_2][$langcode]['#title'], $this->instance_2['label'], "Second field's form title is {$this->instance_2['label']}");
- for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
- // field_test_widget uses 'textfield'
- $this->assertEqual($form[$this->field_name_2][$langcode][$delta]['value']['#type'], 'textfield', "Second field's form delta $delta widget is textfield");
- }
- }
- /**
- * Test field_attach_submit().
- */
- function testFieldAttachSubmit() {
- $this->createFieldWithInstance('_2');
- $entity_type = 'test_entity';
- $entity_init = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $langcode = LANGUAGE_NONE;
- // Build the form for all fields.
- $form = array();
- $form_state = form_state_defaults();
- field_attach_form($entity_type, $entity_init, $form, $form_state);
- // Simulate incoming values.
- // First field.
- $values = array();
- $weights = array();
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- $values[$delta]['value'] = mt_rand(1, 127);
- // Assign random weight.
- do {
- $weight = mt_rand(0, $this->field['cardinality']);
- } while (in_array($weight, $weights));
- $weights[$delta] = $weight;
- $values[$delta]['_weight'] = $weight;
- }
- // Leave an empty value. 'field_test' fields are empty if empty().
- $values[1]['value'] = 0;
- // Second field.
- $values_2 = array();
- $weights_2 = array();
- for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
- $values_2[$delta]['value'] = mt_rand(1, 127);
- // Assign random weight.
- do {
- $weight = mt_rand(0, $this->field_2['cardinality']);
- } while (in_array($weight, $weights_2));
- $weights_2[$delta] = $weight;
- $values_2[$delta]['_weight'] = $weight;
- }
- // Leave an empty value. 'field_test' fields are empty if empty().
- $values_2[1]['value'] = 0;
- // Pretend the form has been built.
- drupal_prepare_form('field_test_entity_form', $form, $form_state);
- drupal_process_form('field_test_entity_form', $form, $form_state);
- $form_state['values'][$this->field_name][$langcode] = $values;
- $form_state['values'][$this->field_name_2][$langcode] = $values_2;
- // Call field_attach_submit() for all fields.
- $entity = clone($entity_init);
- field_attach_submit($entity_type, $entity, $form, $form_state);
- asort($weights);
- asort($weights_2);
- $expected_values = array();
- $expected_values_2 = array();
- foreach ($weights as $key => $value) {
- if ($key != 1) {
- $expected_values[] = array('value' => $values[$key]['value']);
- }
- }
- $this->assertIdentical($entity->{$this->field_name}[$langcode], $expected_values, 'Submit filters empty values');
- foreach ($weights_2 as $key => $value) {
- if ($key != 1) {
- $expected_values_2[] = array('value' => $values_2[$key]['value']);
- }
- }
- $this->assertIdentical($entity->{$this->field_name_2}[$langcode], $expected_values_2, 'Submit filters empty values');
- // Call field_attach_submit() for a single field (the second field).
- $options = array('field_name' => $this->field_name_2);
- $entity = clone($entity_init);
- field_attach_submit($entity_type, $entity, $form, $form_state, $options);
- $expected_values_2 = array();
- foreach ($weights_2 as $key => $value) {
- if ($key != 1) {
- $expected_values_2[] = array('value' => $values_2[$key]['value']);
- }
- }
- $this->assertFalse(isset($entity->{$this->field_name}), 'The first field does not exist in the entity object');
- $this->assertIdentical($entity->{$this->field_name_2}[$langcode], $expected_values_2, 'Submit filters empty values');
- }
- }
- class FieldInfoTestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field info tests',
- 'description' => 'Get information about existing fields, instances and bundles.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- parent::setUp('field_test');
- }
- /**
- * Test that field types and field definitions are correcly cached.
- */
- function testFieldInfo() {
- // Test that field_test module's fields, widgets, and formatters show up.
- $field_test_info = field_test_field_info();
- // We need to account for the existence of user_field_info_alter().
- foreach (array_keys($field_test_info) as $name) {
- $field_test_info[$name]['instance_settings']['user_register_form'] = FALSE;
- }
- $info = field_info_field_types();
- foreach ($field_test_info as $t_key => $field_type) {
- foreach ($field_type as $key => $val) {
- $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))));
- }
- $this->assertEqual($info[$t_key]['module'], 'field_test', "Field type field_test module appears");
- }
- $formatter_info = field_test_field_formatter_info();
- $info = field_info_formatter_types();
- foreach ($formatter_info as $f_key => $formatter) {
- foreach ($formatter as $key => $val) {
- $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))));
- }
- $this->assertEqual($info[$f_key]['module'], 'field_test', "Formatter type field_test module appears");
- }
- $widget_info = field_test_field_widget_info();
- $info = field_info_widget_types();
- foreach ($widget_info as $w_key => $widget) {
- foreach ($widget as $key => $val) {
- $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))));
- }
- $this->assertEqual($info[$w_key]['module'], 'field_test', "Widget type field_test module appears");
- }
- $storage_info = field_test_field_storage_info();
- $info = field_info_storage_types();
- foreach ($storage_info as $s_key => $storage) {
- foreach ($storage as $key => $val) {
- $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))));
- }
- $this->assertEqual($info[$s_key]['module'], 'field_test', "Storage type field_test module appears");
- }
- // Verify that no unexpected instances exist.
- $instances = field_info_instances('test_entity');
- $expected = array('test_bundle' => array());
- $this->assertIdentical($instances, $expected, format_string("field_info_instances('test_entity') returns %expected.", array('%expected' => var_export($expected, TRUE))));
- $instances = field_info_instances('test_entity', 'test_bundle');
- $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'test_bundle') returns an empty array.");
- // Create a field, verify it shows up.
- $core_fields = field_info_fields();
- $field = array(
- 'field_name' => drupal_strtolower($this->randomName()),
- 'type' => 'test_field',
- );
- field_create_field($field);
- $fields = field_info_fields();
- $this->assertEqual(count($fields), count($core_fields) + 1, 'One new field exists');
- $this->assertEqual($fields[$field['field_name']]['field_name'], $field['field_name'], 'info fields contains field name');
- $this->assertEqual($fields[$field['field_name']]['type'], $field['type'], 'info fields contains field type');
- $this->assertEqual($fields[$field['field_name']]['module'], 'field_test', 'info fields contains field module');
- $settings = array('test_field_setting' => 'dummy test string');
- foreach ($settings as $key => $val) {
- $this->assertEqual($fields[$field['field_name']]['settings'][$key], $val, format_string('Field setting %key has correct default value %value', array('%key' => $key, '%value' => $val)));
- }
- $this->assertEqual($fields[$field['field_name']]['cardinality'], 1, 'info fields contains cardinality 1');
- $this->assertEqual($fields[$field['field_name']]['active'], 1, 'info fields contains active 1');
- // Create an instance, verify that it shows up
- $instance = array(
- 'field_name' => $field['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'label' => $this->randomName(),
- 'description' => $this->randomName(),
- 'weight' => mt_rand(0, 127),
- // test_field has no instance settings
- 'widget' => array(
- 'type' => 'test_field_widget',
- 'settings' => array(
- 'test_setting' => 999)));
- field_create_instance($instance);
- $info = entity_get_info('test_entity');
- $instances = field_info_instances('test_entity', $instance['bundle']);
- $this->assertEqual(count($instances), 1, format_string('One instance shows up in info when attached to a bundle on a @label.', array(
- '@label' => $info['label']
- )));
- $this->assertTrue($instance < $instances[$instance['field_name']], 'Instance appears in info correctly');
- // Test a valid entity type but an invalid bundle.
- $instances = field_info_instances('test_entity', 'invalid_bundle');
- $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'invalid_bundle') returns an empty array.");
- // Test invalid entity type and bundle.
- $instances = field_info_instances('invalid_entity', $instance['bundle']);
- $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity', 'test_bundle') returns an empty array.");
- // Test invalid entity type, no bundle provided.
- $instances = field_info_instances('invalid_entity');
- $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity') returns an empty array.");
- // Test with an entity type that has no bundles.
- $instances = field_info_instances('user');
- $expected = array('user' => array());
- $this->assertIdentical($instances, $expected, format_string("field_info_instances('user') returns %expected.", array('%expected' => var_export($expected, TRUE))));
- $instances = field_info_instances('user', 'user');
- $this->assertIdentical($instances, array(), "field_info_instances('user', 'user') returns an empty array.");
- // Test that querying for invalid entity types does not add entries in the
- // list returned by field_info_instances().
- field_info_cache_clear();
- field_info_instances('invalid_entity', 'invalid_bundle');
- // Simulate new request by clearing static caches.
- drupal_static_reset();
- field_info_instances('invalid_entity', 'invalid_bundle');
- $instances = field_info_instances();
- $this->assertFalse(isset($instances['invalid_entity']), 'field_info_instances() does not contain entries for the invalid entity type that was queried before');
- }
- /**
- * Test that cached field definitions are ready for current runtime context.
- */
- function testFieldPrepare() {
- $field_definition = array(
- 'field_name' => 'field',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- // Simulate a stored field definition missing a field setting (e.g. a
- // third-party module adding a new field setting has been enabled, and
- // existing fields do not know the setting yet).
- $data = db_query('SELECT data FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']))->fetchField();
- $data = unserialize($data);
- $data['settings'] = array();
- db_update('field_config')
- ->fields(array('data' => serialize($data)))
- ->condition('field_name', $field_definition['field_name'])
- ->execute();
- field_cache_clear();
- // Read the field back.
- $field = field_info_field($field_definition['field_name']);
- // Check that all expected settings are in place.
- $field_type = field_info_field_types($field_definition['type']);
- $this->assertIdentical($field['settings'], $field_type['settings'], 'All expected default field settings are present.');
- }
- /**
- * Test that cached instance definitions are ready for current runtime context.
- */
- function testInstancePrepare() {
- $field_definition = array(
- 'field_name' => 'field',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $instance_definition = array(
- 'field_name' => $field_definition['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance_definition);
- // Simulate a stored instance definition missing various settings (e.g. a
- // third-party module adding instance, widget or display settings has been
- // enabled, but existing instances do not know the new settings).
- $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();
- $data = unserialize($data);
- $data['settings'] = array();
- $data['widget']['settings'] = 'unavailable_widget';
- $data['widget']['settings'] = array();
- $data['display']['default']['type'] = 'unavailable_formatter';
- $data['display']['default']['settings'] = array();
- db_update('field_config_instance')
- ->fields(array('data' => serialize($data)))
- ->condition('field_name', $instance_definition['field_name'])
- ->condition('bundle', $instance_definition['bundle'])
- ->execute();
- field_cache_clear();
- // Read the instance back.
- $instance = field_info_instance($instance_definition['entity_type'], $instance_definition['field_name'], $instance_definition['bundle']);
- // Check that all expected instance settings are in place.
- $field_type = field_info_field_types($field_definition['type']);
- $this->assertIdentical($instance['settings'], $field_type['instance_settings'] , 'All expected instance settings are present.');
- // Check that the default widget is used and expected settings are in place.
- $this->assertIdentical($instance['widget']['type'], $field_type['default_widget'], 'Unavailable widget replaced with default widget.');
- $widget_type = field_info_widget_types($instance['widget']['type']);
- $this->assertIdentical($instance['widget']['settings'], $widget_type['settings'] , 'All expected widget settings are present.');
- // Check that display settings are set for the 'default' mode.
- $display = $instance['display']['default'];
- $this->assertIdentical($display['type'], $field_type['default_formatter'], "Formatter is set for the 'default' view mode");
- $formatter_type = field_info_formatter_types($display['type']);
- $this->assertIdentical($display['settings'], $formatter_type['settings'] , "Formatter settings are set for the 'default' view mode");
- }
- /**
- * Test that instances on disabled entity types are filtered out.
- */
- function testInstanceDisabledEntityType() {
- // For this test the field type and the entity type must be exposed by
- // different modules.
- $field_definition = array(
- 'field_name' => 'field',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $instance_definition = array(
- 'field_name' => 'field',
- 'entity_type' => 'comment',
- 'bundle' => 'comment_node_article',
- );
- field_create_instance($instance_definition);
- // Disable coment module. This clears field_info cache.
- module_disable(array('comment'));
- $this->assertNull(field_info_instance('comment', 'field', 'comment_node_article'), 'No instances are returned on disabled entity types.');
- }
- /**
- * Test field_info_field_map().
- */
- function testFieldMap() {
- // We will overlook fields created by the 'standard' install profile.
- $exclude = field_info_field_map();
- // Create a new bundle for 'test_entity' entity type.
- field_test_create_bundle('test_bundle_2');
- // Create a couple fields.
- $fields = array(
- array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- ),
- array(
- 'field_name' => 'field_2',
- 'type' => 'hidden_test_field',
- ),
- );
- foreach ($fields as $field) {
- field_create_field($field);
- }
- // Create a couple instances.
- $instances = array(
- array(
- 'field_name' => 'field_1',
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- ),
- array(
- 'field_name' => 'field_1',
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle_2',
- ),
- array(
- 'field_name' => 'field_2',
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- ),
- array(
- 'field_name' => 'field_2',
- 'entity_type' => 'test_cacheable_entity',
- 'bundle' => 'test_bundle',
- ),
- );
- foreach ($instances as $instance) {
- field_create_instance($instance);
- }
- $expected = array(
- 'field_1' => array(
- 'type' => 'test_field',
- 'bundles' => array(
- 'test_entity' => array('test_bundle', 'test_bundle_2'),
- ),
- ),
- 'field_2' => array(
- 'type' => 'hidden_test_field',
- 'bundles' => array(
- 'test_entity' => array('test_bundle'),
- 'test_cacheable_entity' => array('test_bundle'),
- ),
- ),
- );
- // Check that the field map is correct.
- $map = field_info_field_map();
- $map = array_diff_key($map, $exclude);
- $this->assertEqual($map, $expected);
- }
- /**
- * Test that the field_info settings convenience functions work.
- */
- function testSettingsInfo() {
- $info = field_test_field_info();
- // We need to account for the existence of user_field_info_alter().
- foreach (array_keys($info) as $name) {
- $info[$name]['instance_settings']['user_register_form'] = FALSE;
- }
- foreach ($info as $type => $data) {
- $this->assertIdentical(field_info_field_settings($type), $data['settings'], format_string("field_info_field_settings returns %type's field settings", array('%type' => $type)));
- $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)));
- }
- $info = field_test_field_widget_info();
- foreach ($info as $type => $data) {
- $this->assertIdentical(field_info_widget_settings($type), $data['settings'], format_string("field_info_widget_settings returns %type's widget settings", array('%type' => $type)));
- }
- $info = field_test_field_formatter_info();
- foreach ($info as $type => $data) {
- $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], format_string("field_info_formatter_settings returns %type's formatter settings", array('%type' => $type)));
- }
- }
- /**
- * Tests that the field info cache can be built correctly.
- */
- function testFieldInfoCache() {
- // Create a test field and ensure it's in the array returned by
- // field_info_fields().
- $field_name = drupal_strtolower($this->randomName());
- $field = array(
- 'field_name' => $field_name,
- 'type' => 'test_field',
- );
- field_create_field($field);
- $fields = field_info_fields();
- $this->assertTrue(isset($fields[$field_name]), 'The test field is initially found in the array returned by field_info_fields().');
- // Now rebuild the field info cache, and set a variable which will cause
- // the cache to be cleared while it's being rebuilt; see
- // field_test_entity_info(). Ensure the test field is still in the returned
- // array.
- field_info_cache_clear();
- variable_set('field_test_clear_info_cache_in_hook_entity_info', TRUE);
- $fields = field_info_fields();
- $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.');
- }
- }
- class FieldFormTestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field form tests',
- 'description' => 'Test Field form handling.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- parent::setUp('field_test');
- $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
- $this->drupalLogin($web_user);
- $this->field_single = array('field_name' => 'field_single', 'type' => 'test_field');
- $this->field_multiple = array('field_name' => 'field_multiple', 'type' => 'test_field', 'cardinality' => 4);
- $this->field_unlimited = array('field_name' => 'field_unlimited', 'type' => 'test_field', 'cardinality' => FIELD_CARDINALITY_UNLIMITED);
- $this->instance = array(
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'label' => $this->randomName() . '_label',
- 'description' => $this->randomName() . '_description',
- 'weight' => mt_rand(0, 127),
- 'settings' => array(
- 'test_instance_setting' => $this->randomName(),
- ),
- 'widget' => array(
- 'type' => 'test_field_widget',
- 'label' => 'Test Field',
- 'settings' => array(
- 'test_widget_setting' => $this->randomName(),
- )
- )
- );
- }
- function testFieldFormSingle() {
- $this->field = $this->field_single;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Display creation form.
- $this->drupalGet('test-entity/add/test-bundle');
- $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget is displayed');
- $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
- // TODO : check that the widget is populated with default value ?
- // Submit with invalid value (field-level validation).
- $edit = array("{$this->field_name}[$langcode][0][value]" => -1);
- $this->drupalPost(NULL, $edit, t('Save'));
- $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->instance['label'])), 'Field validation fails with invalid input.');
- // TODO : check that the correct field is flagged for error.
- // Create an entity
- $value = mt_rand(1, 127);
- $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
- $this->drupalPost(NULL, $edit, t('Save'));
- preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
- $id = $match[1];
- $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
- $entity = field_test_entity_test_load($id);
- $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
- // Display edit form.
- $this->drupalGet('test-entity/manage/' . $id . '/edit');
- $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", $value, 'Widget is displayed with the correct default value');
- $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
- // Update the entity.
- $value = mt_rand(1, 127);
- $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
- $this->drupalPost(NULL, $edit, t('Save'));
- $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
- $entity = field_test_entity_test_load($id);
- $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was updated');
- // Empty the field.
- $value = '';
- $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
- $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
- $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
- $entity = field_test_entity_test_load($id);
- $this->assertIdentical($entity->{$this->field_name}, array(), 'Field was emptied');
- }
- function testFieldFormSingleRequired() {
- $this->field = $this->field_single;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- $this->instance['required'] = TRUE;
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Submit with missing required value.
- $edit = array();
- $this->drupalPost('test-entity/add/test-bundle', $edit, t('Save'));
- $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
- // Create an entity
- $value = mt_rand(1, 127);
- $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
- $this->drupalPost(NULL, $edit, t('Save'));
- preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
- $id = $match[1];
- $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
- $entity = field_test_entity_test_load($id);
- $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
- // Edit with missing required value.
- $value = '';
- $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
- $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
- $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
- }
- // function testFieldFormMultiple() {
- // $this->field = $this->field_multiple;
- // $this->field_name = $this->field['field_name'];
- // $this->instance['field_name'] = $this->field_name;
- // field_create_field($this->field);
- // field_create_instance($this->instance);
- // }
- function testFieldFormUnlimited() {
- $this->field = $this->field_unlimited;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Display creation form -> 1 widget.
- $this->drupalGet('test-entity/add/test-bundle');
- $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
- $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
- // Press 'add more' button -> 2 widgets.
- $this->drupalPost(NULL, array(), t('Add another item'));
- $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
- $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
- $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
- // TODO : check that non-field inpurs are preserved ('title')...
- // Yet another time so that we can play with more values -> 3 widgets.
- $this->drupalPost(NULL, array(), t('Add another item'));
- // Prepare values and weights.
- $count = 3;
- $delta_range = $count - 1;
- $values = $weights = $pattern = $expected_values = $edit = array();
- for ($delta = 0; $delta <= $delta_range; $delta++) {
- // Assign unique random values and weights.
- do {
- $value = mt_rand(1, 127);
- } while (in_array($value, $values));
- do {
- $weight = mt_rand(-$delta_range, $delta_range);
- } while (in_array($weight, $weights));
- $edit["$this->field_name[$langcode][$delta][value]"] = $value;
- $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
- // We'll need three slightly different formats to check the values.
- $values[$delta] = $value;
- $weights[$delta] = $weight;
- $field_values[$weight]['value'] = (string) $value;
- $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
- }
- // Press 'add more' button -> 4 widgets
- $this->drupalPost(NULL, $edit, t('Add another item'));
- for ($delta = 0; $delta <= $delta_range; $delta++) {
- $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
- $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
- }
- ksort($pattern);
- $pattern = implode('.*', array_values($pattern));
- $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
- $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
- $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
- $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
- // Submit the form and create the entity.
- $this->drupalPost(NULL, $edit, t('Save'));
- preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
- $id = $match[1];
- $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
- $entity = field_test_entity_test_load($id);
- ksort($field_values);
- $field_values = array_values($field_values);
- $this->assertIdentical($entity->{$this->field_name}[$langcode], $field_values, 'Field values were saved in the correct order');
- // Display edit form: check that the expected number of widgets is
- // displayed, with correct values change values, reorder, leave an empty
- // value in the middle.
- // Submit: check that the entity is updated with correct values
- // Re-submit: check that the field can be emptied.
- // Test with several multiple fields in a form
- }
- /**
- * Tests widget handling of multiple required radios.
- */
- function testFieldFormMultivalueWithRequiredRadio() {
- // Create a multivalue test field.
- $this->field = $this->field_unlimited;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Add a required radio field.
- field_create_field(array(
- 'field_name' => 'required_radio_test',
- 'type' => 'list_text',
- 'settings' => array(
- 'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
- ),
- ));
- field_create_instance(array(
- 'field_name' => 'required_radio_test',
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'required' => TRUE,
- 'widget' => array(
- 'type' => 'options_buttons',
- ),
- ));
- // Display creation form.
- $this->drupalGet('test-entity/add/test-bundle');
- // Press the 'Add more' button.
- $this->drupalPost(NULL, array(), t('Add another item'));
- // Verify that no error is thrown by the radio element.
- $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
- // Verify that the widget is added.
- $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
- $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
- $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
- }
- function testFieldFormJSAddMore() {
- $this->field = $this->field_unlimited;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Display creation form -> 1 widget.
- $this->drupalGet('test-entity/add/test-bundle');
- // Press 'add more' button a couple times -> 3 widgets.
- // drupalPostAJAX() will not work iteratively, so we add those through
- // non-JS submission.
- $this->drupalPost(NULL, array(), t('Add another item'));
- $this->drupalPost(NULL, array(), t('Add another item'));
- // Prepare values and weights.
- $count = 3;
- $delta_range = $count - 1;
- $values = $weights = $pattern = $expected_values = $edit = array();
- for ($delta = 0; $delta <= $delta_range; $delta++) {
- // Assign unique random values and weights.
- do {
- $value = mt_rand(1, 127);
- } while (in_array($value, $values));
- do {
- $weight = mt_rand(-$delta_range, $delta_range);
- } while (in_array($weight, $weights));
- $edit["$this->field_name[$langcode][$delta][value]"] = $value;
- $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
- // We'll need three slightly different formats to check the values.
- $values[$delta] = $value;
- $weights[$delta] = $weight;
- $field_values[$weight]['value'] = (string) $value;
- $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
- }
- // Press 'add more' button through Ajax, and place the expected HTML result
- // as the tested content.
- $commands = $this->drupalPostAJAX(NULL, $edit, $this->field_name . '_add_more');
- $this->content = $commands[1]['data'];
- for ($delta = 0; $delta <= $delta_range; $delta++) {
- $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
- $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
- }
- ksort($pattern);
- $pattern = implode('.*', array_values($pattern));
- $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
- $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
- $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
- $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
- }
- /**
- * Tests widgets handling multiple values.
- */
- function testFieldFormMultipleWidget() {
- // Create a field with fixed cardinality and an instance using a multiple
- // widget.
- $this->field = $this->field_multiple;
- $this->field_name = $this->field['field_name'];
- $this->instance['field_name'] = $this->field_name;
- $this->instance['widget']['type'] = 'test_field_widget_multiple';
- field_create_field($this->field);
- field_create_instance($this->instance);
- $langcode = LANGUAGE_NONE;
- // Display creation form.
- $this->drupalGet('test-entity/add/test-bundle');
- $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');
- // Create entity with three values.
- $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3');
- $this->drupalPost(NULL, $edit, t('Save'));
- preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
- $id = $match[1];
- // Check that the values were saved.
- $entity_init = field_test_create_stub_entity($id);
- $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
- // Display the form, check that the values are correctly filled in.
- $this->drupalGet('test-entity/manage/' . $id . '/edit');
- $this->assertFieldByName("{$this->field_name}[$langcode]", '1, 2, 3', 'Widget is displayed.');
- // Submit the form with more values than the field accepts.
- $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3, 4, 5');
- $this->drupalPost(NULL, $edit, t('Save'));
- $this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.');
- // Check that the field values were not submitted.
- $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
- }
- /**
- * Tests fields with no 'edit' access.
- */
- function testFieldFormAccess() {
- // Create a "regular" field.
- $field = $this->field_single;
- $field_name = $field['field_name'];
- $instance = $this->instance;
- $instance['field_name'] = $field_name;
- field_create_field($field);
- field_create_instance($instance);
- // Create a field with no edit access - see field_test_field_access().
- $field_no_access = array(
- 'field_name' => 'field_no_edit_access',
- 'type' => 'test_field',
- );
- $field_name_no_access = $field_no_access['field_name'];
- $instance_no_access = array(
- 'field_name' => $field_name_no_access,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'default_value' => array(0 => array('value' => 99)),
- );
- field_create_field($field_no_access);
- field_create_instance($instance_no_access);
- $langcode = LANGUAGE_NONE;
- // Test that the form structure includes full information for each delta
- // apart from #access.
- $entity_type = 'test_entity';
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- $form = array();
- $form_state = form_state_defaults();
- field_attach_form($entity_type, $entity, $form, $form_state);
- $this->assertEqual($form[$field_name_no_access][$langcode][0]['value']['#entity_type'], $entity_type, 'The correct entity type is set in the field structure.');
- $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
- // Display creation form.
- $this->drupalGet('test-entity/add/test-bundle');
- $this->assertNoFieldByName("{$field_name_no_access}[$langcode][0][value]", '', 'Widget is not displayed if field access is denied.');
- // Create entity.
- $edit = array("{$field_name}[$langcode][0][value]" => 1);
- $this->drupalPost(NULL, $edit, t('Save'));
- preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
- $id = $match[1];
- // Check that the default value was saved.
- $entity = field_test_entity_test_load($id);
- $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'Default value was saved for the field with no edit access.');
- $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 1, 'Entered value vas saved for the field with edit access.');
- // Create a new revision.
- $edit = array("{$field_name}[$langcode][0][value]" => 2, 'revision' => TRUE);
- $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
- // Check that the new revision has the expected values.
- $entity = field_test_entity_test_load($id);
- $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'New revision has the expected value for the field with no edit access.');
- $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, 'New revision has the expected value for the field with edit access.');
- // Check that the revision is also saved in the revisions table.
- $entity = field_test_entity_test_load($id, $entity->ftvid);
- $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'New revision has the expected value for the field with no edit access.');
- $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, 'New revision has the expected value for the field with edit access.');
- }
- /**
- * Tests Field API form integration within a subform.
- */
- function testNestedFieldForm() {
- // Add two instances on the 'test_bundle'
- field_create_field($this->field_single);
- field_create_field($this->field_unlimited);
- $this->instance['field_name'] = 'field_single';
- $this->instance['label'] = 'Single field';
- field_create_instance($this->instance);
- $this->instance['field_name'] = 'field_unlimited';
- $this->instance['label'] = 'Unlimited field';
- field_create_instance($this->instance);
- // Create two entities.
- $entity_1 = field_test_create_stub_entity(1, 1);
- $entity_1->is_new = TRUE;
- $entity_1->field_single[LANGUAGE_NONE][] = array('value' => 0);
- $entity_1->field_unlimited[LANGUAGE_NONE][] = array('value' => 1);
- field_test_entity_save($entity_1);
- $entity_2 = field_test_create_stub_entity(2, 2);
- $entity_2->is_new = TRUE;
- $entity_2->field_single[LANGUAGE_NONE][] = array('value' => 10);
- $entity_2->field_unlimited[LANGUAGE_NONE][] = array('value' => 11);
- field_test_entity_save($entity_2);
- // Display the 'combined form'.
- $this->drupalGet('test-entity/nested/1/2');
- $this->assertFieldByName('field_single[und][0][value]', 0, 'Entity 1: field_single value appears correctly is the form.');
- $this->assertFieldByName('field_unlimited[und][0][value]', 1, 'Entity 1: field_unlimited value 0 appears correctly is the form.');
- $this->assertFieldByName('entity_2[field_single][und][0][value]', 10, 'Entity 2: field_single value appears correctly is the form.');
- $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 11, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
- // Submit the form and check that the entities are updated accordingly.
- $edit = array(
- 'field_single[und][0][value]' => 1,
- 'field_unlimited[und][0][value]' => 2,
- 'field_unlimited[und][1][value]' => 3,
- 'entity_2[field_single][und][0][value]' => 11,
- 'entity_2[field_unlimited][und][0][value]' => 12,
- 'entity_2[field_unlimited][und][1][value]' => 13,
- );
- $this->drupalPost(NULL, $edit, t('Save'));
- field_cache_clear();
- $entity_1 = field_test_create_stub_entity(1);
- $entity_2 = field_test_create_stub_entity(2);
- $this->assertFieldValues($entity_1, 'field_single', LANGUAGE_NONE, array(1));
- $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(2, 3));
- $this->assertFieldValues($entity_2, 'field_single', LANGUAGE_NONE, array(11));
- $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(12, 13));
- // Submit invalid values and check that errors are reported on the
- // correct widgets.
- $edit = array(
- 'field_unlimited[und][1][value]' => -1,
- );
- $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
- $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 1: the field validation error was reported.');
- $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-und-1-value'));
- $this->assertTrue($error_field, 'Entity 1: the error was flagged on the correct element.');
- $edit = array(
- 'entity_2[field_unlimited][und][1][value]' => -1,
- );
- $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
- $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 2: the field validation error was reported.');
- $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-und-1-value'));
- $this->assertTrue($error_field, 'Entity 2: the error was flagged on the correct element.');
- // Test that reordering works on both entities.
- $edit = array(
- 'field_unlimited[und][0][_weight]' => 0,
- 'field_unlimited[und][1][_weight]' => -1,
- 'entity_2[field_unlimited][und][0][_weight]' => 0,
- 'entity_2[field_unlimited][und][1][_weight]' => -1,
- );
- $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
- field_cache_clear();
- $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
- $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 12));
- // Test the 'add more' buttons. Only Ajax submission is tested, because
- // the two 'add more' buttons present in the form have the same #value,
- // which confuses drupalPost().
- // 'Add more' button in the first entity:
- $this->drupalGet('test-entity/nested/1/2');
- $this->drupalPostAJAX(NULL, array(), 'field_unlimited_add_more');
- $this->assertFieldByName('field_unlimited[und][0][value]', 3, 'Entity 1: field_unlimited value 0 appears correctly is the form.');
- $this->assertFieldByName('field_unlimited[und][1][value]', 2, 'Entity 1: field_unlimited value 1 appears correctly is the form.');
- $this->assertFieldByName('field_unlimited[und][2][value]', '', 'Entity 1: field_unlimited value 2 appears correctly is the form.');
- $this->assertFieldByName('field_unlimited[und][3][value]', '', 'Entity 1: an empty widget was added for field_unlimited value 3.');
- // 'Add more' button in the first entity (changing field values):
- $edit = array(
- 'entity_2[field_unlimited][und][0][value]' => 13,
- 'entity_2[field_unlimited][und][1][value]' => 14,
- 'entity_2[field_unlimited][und][2][value]' => 15,
- );
- $this->drupalPostAJAX(NULL, $edit, 'entity_2_field_unlimited_add_more');
- $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 13, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
- $this->assertFieldByName('entity_2[field_unlimited][und][1][value]', 14, 'Entity 2: field_unlimited value 1 appears correctly is the form.');
- $this->assertFieldByName('entity_2[field_unlimited][und][2][value]', 15, 'Entity 2: field_unlimited value 2 appears correctly is the form.');
- $this->assertFieldByName('entity_2[field_unlimited][und][3][value]', '', 'Entity 2: an empty widget was added for field_unlimited value 3.');
- // Save the form and check values are saved correclty.
- $this->drupalPost(NULL, array(), t('Save'));
- field_cache_clear();
- $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
- $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 14, 15));
- }
- }
- class FieldDisplayAPITestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field Display API tests',
- 'description' => 'Test the display API.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- parent::setUp('field_test');
- // Create a field and instance.
- $this->field_name = 'test_field';
- $this->label = $this->randomName();
- $this->cardinality = 4;
- $this->field = array(
- 'field_name' => $this->field_name,
- 'type' => 'test_field',
- 'cardinality' => $this->cardinality,
- );
- $this->instance = array(
- 'field_name' => $this->field_name,
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'label' => $this->label,
- 'display' => array(
- 'default' => array(
- 'type' => 'field_test_default',
- 'settings' => array(
- 'test_formatter_setting' => $this->randomName(),
- ),
- ),
- 'teaser' => array(
- 'type' => 'field_test_default',
- 'settings' => array(
- 'test_formatter_setting' => $this->randomName(),
- ),
- ),
- ),
- );
- field_create_field($this->field);
- field_create_instance($this->instance);
- // Create an entity with values.
- $this->values = $this->_generateTestFieldValues($this->cardinality);
- $this->entity = field_test_create_stub_entity();
- $this->is_new = TRUE;
- $this->entity->{$this->field_name}[LANGUAGE_NONE] = $this->values;
- field_test_entity_save($this->entity);
- }
- /**
- * Test the field_view_field() function.
- */
- function testFieldViewField() {
- // No display settings: check that default display settings are used.
- $output = field_view_field('test_entity', $this->entity, $this->field_name);
- $this->drupalSetContent(drupal_render($output));
- $settings = field_info_formatter_settings('field_test_default');
- $setting = $settings['test_formatter_setting'];
- $this->assertText($this->label, 'Label was displayed.');
- foreach ($this->values as $delta => $value) {
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // Check that explicit display settings are used.
- $display = array(
- 'label' => 'hidden',
- 'type' => 'field_test_multiple',
- 'settings' => array(
- 'test_formatter_setting_multiple' => $this->randomName(),
- 'alter' => TRUE,
- ),
- );
- $output = field_view_field('test_entity', $this->entity, $this->field_name, $display, LANGUAGE_NONE);
- $this->drupalSetContent(drupal_render($output));
- $setting = $display['settings']['test_formatter_setting_multiple'];
- $this->assertNoText($this->label, 'Label was not displayed.');
- $this->assertText('field_test_field_attach_view_alter', 'Alter fired, display passed.');
- $this->assertText('field language is ' . LANGUAGE_NONE, 'Language is placed onto the context.');
- $array = array();
- foreach ($this->values as $delta => $value) {
- $array[] = $delta . ':' . $value['value'];
- }
- $this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
- // Check the prepare_view steps are invoked.
- $display = array(
- 'label' => 'hidden',
- 'type' => 'field_test_with_prepare_view',
- 'settings' => array(
- 'test_formatter_setting_additional' => $this->randomName(),
- ),
- );
- $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
- $view = drupal_render($output);
- $this->drupalSetContent($view);
- $setting = $display['settings']['test_formatter_setting_additional'];
- $this->assertNoText($this->label, 'Label was not displayed.');
- $this->assertNoText('field_test_field_attach_view_alter', 'Alter not fired.');
- foreach ($this->values as $delta => $value) {
- $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // View mode: check that display settings specified in the instance are
- // used.
- $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
- $this->drupalSetContent(drupal_render($output));
- $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
- $this->assertText($this->label, 'Label was displayed.');
- foreach ($this->values as $delta => $value) {
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // Unknown view mode: check that display settings for 'default' view mode
- // are used.
- $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
- $this->drupalSetContent(drupal_render($output));
- $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
- $this->assertText($this->label, 'Label was displayed.');
- foreach ($this->values as $delta => $value) {
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- }
- /**
- * Test the field_view_value() function.
- */
- function testFieldViewValue() {
- // No display settings: check that default display settings are used.
- $settings = field_info_formatter_settings('field_test_default');
- $setting = $settings['test_formatter_setting'];
- foreach ($this->values as $delta => $value) {
- $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
- $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
- $this->drupalSetContent(drupal_render($output));
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // Check that explicit display settings are used.
- $display = array(
- 'type' => 'field_test_multiple',
- 'settings' => array(
- 'test_formatter_setting_multiple' => $this->randomName(),
- ),
- );
- $setting = $display['settings']['test_formatter_setting_multiple'];
- $array = array();
- foreach ($this->values as $delta => $value) {
- $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
- $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
- $this->drupalSetContent(drupal_render($output));
- $this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // Check that prepare_view steps are invoked.
- $display = array(
- 'type' => 'field_test_with_prepare_view',
- 'settings' => array(
- 'test_formatter_setting_additional' => $this->randomName(),
- ),
- );
- $setting = $display['settings']['test_formatter_setting_additional'];
- $array = array();
- foreach ($this->values as $delta => $value) {
- $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
- $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
- $this->drupalSetContent(drupal_render($output));
- $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // View mode: check that display settings specified in the instance are
- // used.
- $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
- foreach ($this->values as $delta => $value) {
- $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
- $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
- $this->drupalSetContent(drupal_render($output));
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- // Unknown view mode: check that display settings for 'default' view mode
- // are used.
- $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
- foreach ($this->values as $delta => $value) {
- $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
- $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
- $this->drupalSetContent(drupal_render($output));
- $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
- }
- }
- }
- class FieldCrudTestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field CRUD tests',
- 'description' => 'Test field create, read, update, and delete.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- // field_update_field() tests use number.module
- parent::setUp('field_test', 'number');
- }
- // TODO : test creation with
- // - a full fledged $field structure, check that all the values are there
- // - a minimal $field structure, check all default values are set
- // defer actual $field comparison to a helper function, used for the two cases above
- /**
- * Test the creation of a field.
- */
- function testCreateField() {
- $field_definition = array(
- 'field_name' => 'field_2',
- 'type' => 'test_field',
- );
- field_test_memorize();
- $field_definition = field_create_field($field_definition);
- $mem = field_test_memorize();
- $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');
- // Read the raw record from the {field_config_instance} table.
- $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
- $record = $result->fetchAssoc();
- $record['data'] = unserialize($record['data']);
- // Ensure that basic properties are preserved.
- $this->assertEqual($record['field_name'], $field_definition['field_name'], 'The field name is properly saved.');
- $this->assertEqual($record['type'], $field_definition['type'], 'The field type is properly saved.');
- // Ensure that cardinality defaults to 1.
- $this->assertEqual($record['cardinality'], 1, 'Cardinality defaults to 1.');
- // Ensure that default settings are present.
- $field_type = field_info_field_types($field_definition['type']);
- $this->assertIdentical($record['data']['settings'], $field_type['settings'], 'Default field settings have been written.');
- // Ensure that default storage was set.
- $this->assertEqual($record['storage_type'], variable_get('field_storage_default'), 'The field type is properly saved.');
- // Guarantee that the name is unique.
- try {
- field_create_field($field_definition);
- $this->fail(t('Cannot create two fields with the same name.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create two fields with the same name.'));
- }
- // Check that field type is required.
- try {
- $field_definition = array(
- 'field_name' => 'field_1',
- );
- field_create_field($field_definition);
- $this->fail(t('Cannot create a field with no type.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create a field with no type.'));
- }
- // Check that field name is required.
- try {
- $field_definition = array(
- 'type' => 'test_field'
- );
- field_create_field($field_definition);
- $this->fail(t('Cannot create an unnamed field.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create an unnamed field.'));
- }
- // Check that field name must start with a letter or _.
- try {
- $field_definition = array(
- 'field_name' => '2field_2',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $this->fail(t('Cannot create a field with a name starting with a digit.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create a field with a name starting with a digit.'));
- }
- // Check that field name must only contain lowercase alphanumeric or _.
- try {
- $field_definition = array(
- 'field_name' => 'field#_3',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $this->fail(t('Cannot create a field with a name containing an illegal character.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create a field with a name containing an illegal character.'));
- }
- // Check that field name cannot be longer than 32 characters long.
- try {
- $field_definition = array(
- 'field_name' => '_12345678901234567890123456789012',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
- }
- // Check that field name can not be an entity key.
- // "ftvid" is known as an entity key from the "test_entity" type.
- try {
- $field_definition = array(
- 'type' => 'test_field',
- 'field_name' => 'ftvid',
- );
- $field = field_create_field($field_definition);
- $this->fail(t('Cannot create a field bearing the name of an entity key.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create a field bearing the name of an entity key.'));
- }
- }
- /**
- * Test failure to create a field.
- */
- function testCreateFieldFail() {
- $field_name = 'duplicate';
- $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
- $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();
- // The field does not appear in field_config.
- $count = $query->execute()->fetchField();
- $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
- // Try to create the field.
- try {
- $field = field_create_field($field_definition);
- $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
- }
- catch (Exception $e) {
- $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
- }
- // The field does not appear in field_config.
- $count = $query->execute()->fetchField();
- $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
- }
- /**
- * Test reading back a field definition.
- */
- function testReadField() {
- $field_definition = array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- // Read the field back.
- $field = field_read_field($field_definition['field_name']);
- $this->assertTrue($field_definition < $field, 'The field was properly read.');
- }
- /**
- * Tests reading field definitions.
- */
- function testReadFields() {
- $field_definition = array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- // Check that 'single column' criteria works.
- $fields = field_read_fields(array('field_name' => $field_definition['field_name']));
- $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
- // Check that 'multi column' criteria works.
- $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => $field_definition['type']));
- $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
- $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => 'foo'));
- $this->assertTrue(empty($fields), 'No field was found.');
- // Create an instance of the field.
- $instance_definition = array(
- 'field_name' => $field_definition['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance_definition);
- // Check that criteria spanning over the field_config_instance table work.
- $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'bundle' => $instance_definition['bundle']));
- $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
- $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'field_name' => $instance_definition['field_name']));
- $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
- }
- /**
- * Test creation of indexes on data column.
- */
- function testFieldIndexes() {
- // Check that indexes specified by the field type are used by default.
- $field_definition = array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- );
- field_create_field($field_definition);
- $field = field_read_field($field_definition['field_name']);
- $expected_indexes = array('value' => array('value'));
- $this->assertEqual($field['indexes'], $expected_indexes, 'Field type indexes saved by default');
- // Check that indexes specified by the field definition override the field
- // type indexes.
- $field_definition = array(
- 'field_name' => 'field_2',
- 'type' => 'test_field',
- 'indexes' => array(
- 'value' => array(),
- ),
- );
- field_create_field($field_definition);
- $field = field_read_field($field_definition['field_name']);
- $expected_indexes = array('value' => array());
- $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes override field type indexes');
- // Check that indexes specified by the field definition add to the field
- // type indexes.
- $field_definition = array(
- 'field_name' => 'field_3',
- 'type' => 'test_field',
- 'indexes' => array(
- 'value_2' => array('value'),
- ),
- );
- field_create_field($field_definition);
- $field = field_read_field($field_definition['field_name']);
- $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
- $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes are merged with field type indexes');
- }
- /**
- * Test the deletion of a field.
- */
- function testDeleteField() {
- // TODO: Also test deletion of the data stored in the field ?
- // Create two fields (so we can test that only one is deleted).
- $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
- field_create_field($this->field);
- $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
- field_create_field($this->another_field);
- // Create instances for each.
- $this->instance_definition = array(
- 'field_name' => $this->field['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- 'widget' => array(
- 'type' => 'test_field_widget',
- ),
- );
- field_create_instance($this->instance_definition);
- $this->another_instance_definition = $this->instance_definition;
- $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
- field_create_instance($this->another_instance_definition);
- // Test that the first field is not deleted, and then delete it.
- $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($field) && empty($field['deleted']), 'A new field is not marked for deletion.');
- field_delete_field($this->field['field_name']);
- // Make sure that the field is marked as deleted when it is specifically
- // loaded.
- $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion.');
- // Make sure that this field's instance is marked as deleted when it is
- // specifically loaded.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($instance['deleted']), 'An instance for a deleted field is marked for deletion.');
- // Try to load the field normally and make sure it does not show up.
- $field = field_read_field($this->field['field_name']);
- $this->assertTrue(empty($field), 'A deleted field is not loaded by default.');
- // Try to load the instance normally and make sure it does not show up.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertTrue(empty($instance), 'An instance for a deleted field is not loaded by default.');
- // Make sure the other field (and its field instance) are not deleted.
- $another_field = field_read_field($this->another_field['field_name']);
- $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), 'A non-deleted field is not marked for deletion.');
- $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
- $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), 'An instance of a non-deleted field is not marked for deletion.');
- // Try to create a new field the same name as a deleted field and
- // write data into it.
- field_create_field($this->field);
- field_create_instance($this->instance_definition);
- $field = field_read_field($this->field['field_name']);
- $this->assertTrue(!empty($field) && empty($field['deleted']), 'A new field with a previously used name is created.');
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertTrue(!empty($instance) && empty($instance['deleted']), 'A new instance for a previously used field name is created.');
- // Save an entity with data for the field
- $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
- $langcode = LANGUAGE_NONE;
- $values[0]['value'] = mt_rand(1, 127);
- $entity->{$field['field_name']}[$langcode] = $values;
- $entity_type = 'test_entity';
- field_attach_insert('test_entity', $entity);
- // Verify the field is present on load
- $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
- field_attach_load($entity_type, array(0 => $entity));
- $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
- foreach ($values as $delta => $value) {
- $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
- }
- }
- function testUpdateNonExistentField() {
- $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
- try {
- field_update_field($test_field);
- $this->fail(t('Cannot update a field that does not exist.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot update a field that does not exist.'));
- }
- }
- function testUpdateFieldType() {
- $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
- $field = field_create_field($field);
- $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
- try {
- field_update_field($test_field);
- $this->fail(t('Cannot update a field to a different type.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot update a field to a different type.'));
- }
- }
- /**
- * Test updating a field.
- */
- function testUpdateField() {
- // Create a field with a defined cardinality, so that we can ensure it's
- // respected. Since cardinality enforcement is consistent across database
- // systems, it makes a good test case.
- $cardinality = 4;
- $field_definition = array(
- 'field_name' => 'field_update',
- 'type' => 'test_field',
- 'cardinality' => $cardinality,
- );
- $field_definition = field_create_field($field_definition);
- $instance = array(
- 'field_name' => 'field_update',
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- $instance = field_create_instance($instance);
- do {
- // We need a unique ID for our entity. $cardinality will do.
- $id = $cardinality;
- $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
- // Fill in the entity with more values than $cardinality.
- for ($i = 0; $i < 20; $i++) {
- $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
- }
- // Save the entity.
- field_attach_insert('test_entity', $entity);
- // Load back and assert there are $cardinality number of values.
- $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
- field_attach_load('test_entity', array($id => $entity));
- $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
- // Now check the values themselves.
- for ($delta = 0; $delta < $cardinality; $delta++) {
- $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
- }
- // Increase $cardinality and set the field cardinality to the new value.
- $field_definition['cardinality'] = ++$cardinality;
- field_update_field($field_definition);
- } while ($cardinality < 6);
- }
- /**
- * Test field type modules forbidding an update.
- */
- function testUpdateFieldForbid() {
- $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
- $field = field_create_field($field);
- $field['settings']['changeable']++;
- try {
- field_update_field($field);
- $this->pass(t("A changeable setting can be updated."));
- }
- catch (FieldException $e) {
- $this->fail(t("An unchangeable setting cannot be updated."));
- }
- $field['settings']['unchangeable']++;
- try {
- field_update_field($field);
- $this->fail(t("An unchangeable setting can be updated."));
- }
- catch (FieldException $e) {
- $this->pass(t("An unchangeable setting cannot be updated."));
- }
- }
- /**
- * Test that fields are properly marked active or inactive.
- */
- function testActive() {
- $field_definition = array(
- 'field_name' => 'field_1',
- 'type' => 'test_field',
- // For this test, we need a storage backend provided by a different
- // module than field_test.module.
- 'storage' => array(
- 'type' => 'field_sql_storage',
- ),
- );
- field_create_field($field_definition);
- // Test disabling and enabling:
- // - the field type module,
- // - the storage module,
- // - both.
- $this->_testActiveHelper($field_definition, array('field_test'));
- $this->_testActiveHelper($field_definition, array('field_sql_storage'));
- $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
- }
- /**
- * Helper function for testActive().
- *
- * Test dependency between a field and a set of modules.
- *
- * @param $field_definition
- * A field definition.
- * @param $modules
- * An aray of module names. The field will be tested to be inactive as long
- * as any of those modules is disabled.
- */
- function _testActiveHelper($field_definition, $modules) {
- $field_name = $field_definition['field_name'];
- // Read the field.
- $field = field_read_field($field_name);
- $this->assertTrue($field_definition <= $field, 'The field was properly read.');
- module_disable($modules, FALSE);
- $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
- $this->assertTrue(isset($fields[$field_name]) && $field_definition < $field, 'The field is properly read when explicitly fetching inactive fields.');
- // Re-enable modules one by one, and check that the field is still inactive
- // while some modules remain disabled.
- while ($modules) {
- $field = field_read_field($field_name);
- $this->assertTrue(empty($field), format_string('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));
- $module = array_shift($modules);
- module_enable(array($module), FALSE);
- }
- // Check that the field is active again after all modules have been
- // enabled.
- $field = field_read_field($field_name);
- $this->assertTrue($field_definition <= $field, 'The field was was marked active.');
- }
- }
- class FieldInstanceCrudTestCase extends FieldTestCase {
- protected $field;
- public static function getInfo() {
- return array(
- 'name' => 'Field instance CRUD tests',
- 'description' => 'Create field entities by attaching fields to entities.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- parent::setUp('field_test');
- $this->field = array(
- 'field_name' => drupal_strtolower($this->randomName()),
- 'type' => 'test_field',
- );
- field_create_field($this->field);
- $this->instance_definition = array(
- 'field_name' => $this->field['field_name'],
- 'entity_type' => 'test_entity',
- 'bundle' => 'test_bundle',
- );
- }
- // TODO : test creation with
- // - a full fledged $instance structure, check that all the values are there
- // - a minimal $instance structure, check all default values are set
- // defer actual $instance comparison to a helper function, used for the two cases above,
- // and for testUpdateFieldInstance
- /**
- * Test the creation of a field instance.
- */
- function testCreateFieldInstance() {
- field_create_instance($this->instance_definition);
- // Read the raw record from the {field_config_instance} table.
- $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']));
- $record = $result->fetchAssoc();
- $record['data'] = unserialize($record['data']);
- $field_type = field_info_field_types($this->field['type']);
- $widget_type = field_info_widget_types($field_type['default_widget']);
- $formatter_type = field_info_formatter_types($field_type['default_formatter']);
- // Check that default values are set.
- $this->assertIdentical($record['data']['required'], FALSE, 'Required defaults to false.');
- $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], 'Label defaults to field name.');
- $this->assertIdentical($record['data']['description'], '', 'Description defaults to empty string.');
- $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], 'Default widget has been written.');
- $this->assertTrue(isset($record['data']['display']['default']), 'Display for "full" view_mode has been written.');
- $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], 'Default formatter for "full" view_mode has been written.');
- // Check that default settings are set.
- $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , 'Default instance settings have been written.');
- $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , 'Default widget settings have been written.');
- $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], 'Default formatter settings for "full" view_mode have been written.');
- // Guarantee that the field/bundle combination is unique.
- try {
- field_create_instance($this->instance_definition);
- $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
- }
- // Check that the specified field exists.
- try {
- $this->instance_definition['field_name'] = $this->randomName();
- field_create_instance($this->instance_definition);
- $this->fail(t('Cannot create an instance of a non-existing field.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create an instance of a non-existing field.'));
- }
- // Create a field restricted to a specific entity type.
- $field_restricted = array(
- 'field_name' => drupal_strtolower($this->randomName()),
- 'type' => 'test_field',
- 'entity_types' => array('test_cacheable_entity'),
- );
- field_create_field($field_restricted);
- // Check that an instance can be added to an entity type allowed
- // by the field.
- try {
- $instance = $this->instance_definition;
- $instance['field_name'] = $field_restricted['field_name'];
- $instance['entity_type'] = 'test_cacheable_entity';
- field_create_instance($instance);
- $this->pass(t('Can create an instance on an entity type allowed by the field.'));
- }
- catch (FieldException $e) {
- $this->fail(t('Can create an instance on an entity type allowed by the field.'));
- }
- // Check that an instance cannot be added to an entity type
- // forbidden by the field.
- try {
- $instance = $this->instance_definition;
- $instance['field_name'] = $field_restricted['field_name'];
- field_create_instance($instance);
- $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
- }
- catch (FieldException $e) {
- $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
- }
- // TODO: test other failures.
- }
- /**
- * Test reading back an instance definition.
- */
- function testReadFieldInstance() {
- field_create_instance($this->instance_definition);
- // Read the instance back.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertTrue($this->instance_definition < $instance, 'The field was properly read.');
- }
- /**
- * Test the update of a field instance.
- */
- function testUpdateFieldInstance() {
- field_create_instance($this->instance_definition);
- $field_type = field_info_field_types($this->field['type']);
- // Check that basic changes are saved.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $instance['required'] = !$instance['required'];
- $instance['label'] = $this->randomName();
- $instance['description'] = $this->randomName();
- $instance['settings']['test_instance_setting'] = $this->randomName();
- $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
- $instance['widget']['weight']++;
- $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
- $instance['display']['default']['weight']++;
- field_update_instance($instance);
- $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertEqual($instance['required'], $instance_new['required'], '"required" change is saved');
- $this->assertEqual($instance['label'], $instance_new['label'], '"label" change is saved');
- $this->assertEqual($instance['description'], $instance_new['description'], '"description" change is saved');
- $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], 'Widget setting change is saved');
- $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], 'Widget weight change is saved');
- $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], 'Formatter setting change is saved');
- $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], 'Widget weight change is saved');
- // Check that changing widget and formatter types updates the default settings.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $instance['widget']['type'] = 'test_field_widget_multiple';
- $instance['display']['default']['type'] = 'field_test_multiple';
- field_update_instance($instance);
- $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , 'Widget type change is saved.');
- $settings = field_info_widget_settings($instance_new['widget']['type']);
- $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , 'Widget type change updates default settings.');
- $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , 'Formatter type change is saved.');
- $info = field_info_formatter_types($instance_new['display']['default']['type']);
- $settings = $info['settings'];
- $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , 'Changing formatter type updates default settings.');
- // Check that adding a new view mode is saved and gets default settings.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $instance['display']['teaser'] = array();
- field_update_instance($instance);
- $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertTrue(isset($instance_new['display']['teaser']), 'Display for the new view_mode has been written.');
- $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], 'Default formatter for the new view_mode has been written.');
- $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
- $settings = $info['settings'];
- $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , 'Default formatter settings for the new view_mode have been written.');
- // TODO: test failures.
- }
- /**
- * Test the deletion of a field instance.
- */
- function testDeleteFieldInstance() {
- // TODO: Test deletion of the data stored in the field also.
- // Need to check that data for a 'deleted' field / instance doesn't get loaded
- // Need to check data marked deleted is cleaned on cron (not implemented yet...)
- // Create two instances for the same field so we can test that only one
- // is deleted.
- field_create_instance($this->instance_definition);
- $this->another_instance_definition = $this->instance_definition;
- $this->another_instance_definition['bundle'] .= '_another_bundle';
- $instance = field_create_instance($this->another_instance_definition);
- // Test that the first instance is not deleted, and then delete it.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($instance) && empty($instance['deleted']), 'A new field instance is not marked for deletion.');
- field_delete_instance($instance);
- // Make sure the instance is marked as deleted when the instance is
- // specifically loaded.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($instance['deleted']), 'A deleted field instance is marked for deletion.');
- // Try to load the instance normally and make sure it does not show up.
- $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
- $this->assertTrue(empty($instance), 'A deleted field instance is not loaded by default.');
- // Make sure the other field instance is not deleted.
- $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
- $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), 'A non-deleted field instance is not marked for deletion.');
- // Make sure the field is deleted when its last instance is deleted.
- field_delete_instance($another_instance);
- $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
- $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion after all its instances have been marked for deletion.');
- }
- }
- /**
- * Unit test class for the multilanguage fields logic.
- *
- * The following tests will check the multilanguage logic of _field_invoke() and
- * that only the correct values are returned by field_available_languages().
- */
- class FieldTranslationsTestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Field translations tests',
- 'description' => 'Test multilanguage fields logic.',
- 'group' => 'Field API',
- );
- }
- function setUp() {
- parent::setUp('locale', 'field_test');
- $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
- $this->entity_type = 'test_entity';
- $field = array(
- 'field_name' => $this->field_name,
- 'type' => 'test_field',
- 'cardinality' => 4,
- 'translatable' => TRUE,
- );
- field_create_field($field);
- $this->field = field_read_field($this->field_name);
- $instance = array(
- 'field_name' => $this->field_name,
- 'entity_type' => $this->entity_type,
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance);
- $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');
- require_once DRUPAL_ROOT . '/includes/locale.inc';
- for ($i = 0; $i < 3; ++$i) {
- locale_add_language('l' . $i, $this->randomString(), $this->randomString());
- }
- }
- /**
- * Ensures that only valid values are returned by field_available_languages().
- */
- function testFieldAvailableLanguages() {
- // Test 'translatable' fieldable info.
- field_test_entity_info_translatable('test_entity', FALSE);
- $field = $this->field;
- $field['field_name'] .= '_untranslatable';
- // Enable field translations for the entity.
- field_test_entity_info_translatable('test_entity', TRUE);
- // Test hook_field_languages() invocation on a translatable field.
- variable_set('field_test_field_available_languages_alter', TRUE);
- $enabled_languages = field_content_languages();
- $available_languages = field_available_languages($this->entity_type, $this->field);
- foreach ($available_languages as $delta => $langcode) {
- if ($langcode != 'xx' && $langcode != 'en') {
- $this->assertTrue(in_array($langcode, $enabled_languages), format_string('%language is an enabled language.', array('%language' => $langcode)));
- }
- }
- $this->assertTrue(in_array('xx', $available_languages), format_string('%language was made available.', array('%language' => 'xx')));
- $this->assertFalse(in_array('en', $available_languages), format_string('%language was made unavailable.', array('%language' => 'en')));
- // Test field_available_languages() behavior for untranslatable fields.
- $this->field['translatable'] = FALSE;
- field_update_field($this->field);
- $available_languages = field_available_languages($this->entity_type, $this->field);
- $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, 'For untranslatable fields only LANGUAGE_NONE is available.');
- }
- /**
- * Test the multilanguage logic of _field_invoke().
- */
- function testFieldInvoke() {
- // Enable field translations for the entity.
- field_test_entity_info_translatable('test_entity', TRUE);
- $entity_type = 'test_entity';
- $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
- // Populate some extra languages to check if _field_invoke() correctly uses
- // the result of field_available_languages().
- $values = array();
- $extra_languages = mt_rand(1, 4);
- $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
- for ($i = 0; $i < $extra_languages; ++$i) {
- $languages[] = $this->randomName(2);
- }
- // For each given language provide some random values.
- foreach ($languages as $langcode) {
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- $values[$langcode][$delta]['value'] = mt_rand(1, 127);
- }
- }
- $entity->{$this->field_name} = $values;
- $results = _field_invoke('test_op', $entity_type, $entity);
- foreach ($results as $langcode => $result) {
- $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
- // Check whether the parameters passed to _field_invoke() were correctly
- // forwarded to the callback function.
- $this->assertEqual($hash, $result, format_string('The result for %language is correctly stored.', array('%language' => $langcode)));
- }
- $this->assertEqual(count($results), count($available_languages), 'No unavailable language has been processed.');
- }
- /**
- * Test the multilanguage logic of _field_invoke_multiple().
- */
- function testFieldInvokeMultiple() {
- // Enable field translations for the entity.
- field_test_entity_info_translatable('test_entity', TRUE);
- $values = array();
- $options = array();
- $entities = array();
- $entity_type = 'test_entity';
- $entity_count = 5;
- $available_languages = field_available_languages($this->entity_type, $this->field);
- for ($id = 1; $id <= $entity_count; ++$id) {
- $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
- $languages = $available_languages;
- // Populate some extra languages to check whether _field_invoke()
- // correctly uses the result of field_available_languages().
- $extra_languages = mt_rand(1, 4);
- for ($i = 0; $i < $extra_languages; ++$i) {
- $languages[] = $this->randomName(2);
- }
- // For each given language provide some random values.
- $language_count = count($languages);
- for ($i = 0; $i < $language_count; ++$i) {
- $langcode = $languages[$i];
- // Avoid to populate at least one field translation to check that
- // per-entity language suggestions work even when available field values
- // are different for each language.
- if ($i !== $id) {
- for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
- $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
- }
- }
- // Ensure that a language for which there is no field translation is
- // used as display language to prepare per-entity language suggestions.
- elseif (!isset($display_language)) {
- $display_language = $langcode;
- }
- }
- $entity->{$this->field_name} = $values[$id];
- $entities[$id] = $entity;
- // Store per-entity language suggestions.
- $options['language'][$id] = field_language($entity_type, $entity, NULL, $display_language);
- }
- $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
- foreach ($grouped_results as $id => $results) {
- foreach ($results as $langcode => $result) {
- if (isset($values[$id][$langcode])) {
- $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
- // Check whether the parameters passed to _field_invoke_multiple()
- // were correctly forwarded to the callback function.
- $this->assertEqual($hash, $result, format_string('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
- }
- }
- $this->assertEqual(count($results), count($available_languages), format_string('No unavailable language has been processed for entity %id.', array('%id' => $id)));
- }
- $null = NULL;
- $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities, $null, $null, $options);
- foreach ($grouped_results as $id => $results) {
- foreach ($results as $langcode => $result) {
- $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)));
- }
- }
- }
- /**
- * Test translatable fields storage/retrieval.
- */
- function testTranslatableFieldSaveLoad() {
- // Enable field translations for nodes.
- field_test_entity_info_translatable('node', TRUE);
- $entity_info = entity_get_info('node');
- $this->assertTrue(count($entity_info['translation']), 'Nodes are translatable.');
- // Prepare the field translations.
- field_test_entity_info_translatable('test_entity', TRUE);
- $eid = $evid = 1;
- $entity_type = 'test_entity';
- $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
- $field_translations = array();
- $available_languages = field_available_languages($entity_type, $this->field);
- $this->assertTrue(count($available_languages) > 1, 'Field is translatable.');
- foreach ($available_languages as $langcode) {
- $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
- }
- // Save and reload the field translations.
- $entity->{$this->field_name} = $field_translations;
- field_attach_insert($entity_type, $entity);
- unset($entity->{$this->field_name});
- field_attach_load($entity_type, array($eid => $entity));
- // Check if the correct values were saved/loaded.
- foreach ($field_translations as $langcode => $items) {
- $result = TRUE;
- foreach ($items as $delta => $item) {
- $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
- }
- $this->assertTrue($result, format_string('%language translation correctly handled.', array('%language' => $langcode)));
- }
- }
- /**
- * Tests display language logic for translatable fields.
- */
- function testFieldDisplayLanguage() {
- $field_name = drupal_strtolower($this->randomName() . '_field_name');
- $entity_type = 'test_entity';
- // We need an additional field here to properly test display language
- // suggestions.
- $field = array(
- 'field_name' => $field_name,
- 'type' => 'test_field',
- 'cardinality' => 2,
- 'translatable' => TRUE,
- );
- field_create_field($field);
- $instance = array(
- 'field_name' => $field['field_name'],
- 'entity_type' => $entity_type,
- 'bundle' => 'test_bundle',
- );
- field_create_instance($instance);
- $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
- $instances = field_info_instances($entity_type, $this->instance['bundle']);
- $enabled_languages = field_content_languages();
- $languages = array();
- // Generate field translations for languages different from the first
- // enabled.
- foreach ($instances as $instance) {
- $field_name = $instance['field_name'];
- $field = field_info_field($field_name);
- do {
- // Index 0 is reserved for the requested language, this way we ensure
- // that no field is actually populated with it.
- $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
- }
- while (isset($languages[$langcode]));
- $languages[$langcode] = TRUE;
- $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
- }
- // Test multiple-fields display languages for untranslatable entities.
- field_test_entity_info_translatable($entity_type, FALSE);
- drupal_static_reset('field_language');
- $requested_language = $enabled_languages[0];
- $display_language = field_language($entity_type, $entity, NULL, $requested_language);
- foreach ($instances as $instance) {
- $field_name = $instance['field_name'];
- $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)));
- }
- // Test multiple-fields display languages for translatable entities.
- field_test_entity_info_translatable($entity_type, TRUE);
- drupal_static_reset('field_language');
- $display_language = field_language($entity_type, $entity, NULL, $requested_language);
- foreach ($instances as $instance) {
- $field_name = $instance['field_name'];
- $langcode = $display_language[$field_name];
- // As the requested language was not assinged to any field, if the
- // returned language is defined for the current field, core fallback rules
- // were successfully applied.
- $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)));
- }
- // Test single-field display language.
- drupal_static_reset('field_language');
- $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
- $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)));
- // Test field_language() basic behavior without language fallback.
- variable_set('field_test_language_fallback', FALSE);
- $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
- drupal_static_reset('field_language');
- $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
- $this->assertEqual($display_language, $requested_language, 'Display language behave correctly when language fallback is disabled');
- }
- /**
- * Tests field translations when creating a new revision.
- */
- function testFieldFormTranslationRevisions() {
- $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
- $this->drupalLogin($web_user);
- // Prepare the field translations.
- field_test_entity_info_translatable($this->entity_type, TRUE);
- $eid = 1;
- $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
- $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
- unset($available_languages[LANGUAGE_NONE]);
- $field_name = $this->field['field_name'];
- // Store the field translations.
- $entity->is_new = TRUE;
- foreach ($available_languages as $langcode => $value) {
- $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
- }
- field_test_entity_save($entity);
- // Create a new revision.
- $langcode = field_valid_language(NULL);
- $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
- $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));
- // Check translation revisions.
- $this->checkTranslationRevisions($eid, $eid, $available_languages);
- $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
- }
- /**
- * Check if the field translation attached to the entity revision identified
- * by the passed arguments were correctly stored.
- */
- private function checkTranslationRevisions($eid, $evid, $available_languages) {
- $field_name = $this->field['field_name'];
- $entity = field_test_entity_test_load($eid, $evid);
- foreach ($available_languages as $langcode => $value) {
- $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
- $this->assertTrue($passed, format_string('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
- }
- }
- }
- /**
- * Unit test class for field bulk delete and batch purge functionality.
- */
- class FieldBulkDeleteTestCase extends FieldTestCase {
- protected $field;
- public static function getInfo() {
- return array(
- 'name' => 'Field bulk delete tests',
- 'description' => 'Bulk delete fields and instances, and clean up afterwards.',
- 'group' => 'Field API',
- );
- }
- /**
- * Convenience function for Field API tests.
- *
- * Given an array of potentially fully-populated entities and an
- * optional field name, generate an array of stub entities of the
- * same fieldable type which contains the data for the field name
- * (if given).
- *
- * @param $entity_type
- * The entity type of $entities.
- * @param $entities
- * An array of entities of type $entity_type.
- * @param $field_name
- * Optional; a field name whose data should be copied from
- * $entities into the returned stub entities.
- * @return
- * An array of stub entities corresponding to $entities.
- */
- function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
- $stubs = array();
- foreach ($entities as $id => $entity) {
- $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
- if (isset($field_name)) {
- $stub->{$field_name} = $entity->{$field_name};
- }
- $stubs[$id] = $stub;
- }
- return $stubs;
- }
- /**
- * Tests that the expected hooks have been invoked on the expected entities.
- *
- * @param $expected_hooks
- * An array keyed by hook name, with one entry per expected invocation.
- * Each entry is the value of the "$entity" parameter the hook is expected
- * to have been passed.
- * @param $actual_hooks
- * The array of actual hook invocations recorded by field_test_memorize().
- */
- function checkHooksInvocations($expected_hooks, $actual_hooks) {
- foreach ($expected_hooks as $hook => $invocations) {
- $actual_invocations = $actual_hooks[$hook];
- // Check that the number of invocations is correct.
- $this->assertEqual(count($actual_invocations), count($invocations), "$hook() was called the expected number of times.");
- // Check that the hook was called for each expected argument.
- foreach ($invocations as $argument) {
- $found = FALSE;
- foreach ($actual_invocations as $actual_arguments) {
- if ($actual_arguments[1] == $argument) {
- $found = TRUE;
- break;
- }
- }
- $this->assertTrue($found, "$hook() was called on expected argument");
- }
- }
- }
- function setUp() {
- parent::setUp('field_test');
- $this->fields = array();
- $this->instances = array();
- $this->entities = array();
- $this->entities_by_bundles = array();
- // Create two bundles.
- $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
- foreach ($this->bundles as $name => $desc) {
- field_test_create_bundle($name, $desc);
- }
- // Create two fields.
- $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
- $this->fields[] = field_create_field($field);
- $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
- $this->fields[] = field_create_field($field);
- // For each bundle, create an instance of each field, and 10
- // entities with values for each field.
- $id = 0;
- $this->entity_type = 'test_entity';
- foreach ($this->bundles as $bundle) {
- foreach ($this->fields as $field) {
- $instance = array(
- 'field_name' => $field['field_name'],
- 'entity_type' => $this->entity_type,
- 'bundle' => $bundle,
- 'widget' => array(
- 'type' => 'test_field_widget',
- )
- );
- $this->instances[] = field_create_instance($instance);
- }
- for ($i = 0; $i < 10; $i++) {
- $entity = field_test_create_stub_entity($id, $id, $bundle);
- foreach ($this->fields as $field) {
- $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
- }
- $this->entities[$id] = $entity;
- // Also keep track of the entities per bundle.
- $this->entities_by_bundles[$bundle][$id] = $entity;
- field_attach_insert($this->entity_type, $entity);
- $id++;
- }
- }
- }
- /**
- * Verify that deleting an instance leaves the field data items in
- * the database and that the appropriate Field API functions can
- * operate on the deleted data and instance.
- *
- * This tests how EntityFieldQuery interacts with
- * field_delete_instance() and could be moved to FieldCrudTestCase,
- * but depends on this class's setUp().
- */
- function testDeleteFieldInstance() {
- $bundle = reset($this->bundles);
- $field = reset($this->fields);
- // There are 10 entities of this bundle.
- $query = new EntityFieldQuery();
- $found = $query
- ->fieldCondition($field)
- ->entityCondition('bundle', $bundle)
- ->execute();
- $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');
- // Delete the instance.
- $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
- field_delete_instance($instance);
- // The instance still exists, deleted.
- $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
- $this->assertEqual(count($instances), 1, 'There is one deleted instance');
- $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');
- // There are 0 entities of this bundle with non-deleted data.
- $query = new EntityFieldQuery();
- $found = $query
- ->fieldCondition($field)
- ->entityCondition('bundle', $bundle)
- ->execute();
- $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');
- // There are 10 entities of this bundle when deleted fields are allowed, and
- // their values are correct.
- $query = new EntityFieldQuery();
- $found = $query
- ->fieldCondition($field)
- ->entityCondition('bundle', $bundle)
- ->deleted(TRUE)
- ->execute();
- field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
- $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
- foreach ($found['test_entity'] as $id => $entity) {
- $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
- }
- }
- /**
- * Verify that field data items and instances are purged when an
- * instance is deleted.
- */
- function testPurgeInstance() {
- // Start recording hook invocations.
- field_test_memorize();
- $bundle = reset($this->bundles);
- $field = reset($this->fields);
- // Delete the instance.
- $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
- field_delete_instance($instance);
- // No field hooks were called.
- $mem = field_test_memorize();
- $this->assertEqual(count($mem), 0, 'No field hooks were called');
- $batch_size = 2;
- for ($count = 8; $count >= 0; $count -= $batch_size) {
- // Purge two entities.
- field_purge_batch($batch_size);
- // There are $count deleted entities left.
- $query = new EntityFieldQuery();
- $found = $query
- ->fieldCondition($field)
- ->entityCondition('bundle', $bundle)
- ->deleted(TRUE)
- ->execute();
- $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
- }
- // Check hooks invocations.
- // - hook_field_load() (multiple hook) should have been called on all
- // entities by pairs of two.
- // - hook_field_delete() should have been called once for each entity in the
- // bundle.
- $actual_hooks = field_test_memorize();
- $hooks = array();
- $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
- foreach (array_chunk($stubs, $batch_size, TRUE) as $chunk) {
- $hooks['field_test_field_load'][] = $chunk;
- }
- foreach ($stubs as $stub) {
- $hooks['field_test_field_delete'][] = $stub;
- }
- $this->checkHooksInvocations($hooks, $actual_hooks);
- // The instance still exists, deleted.
- $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
- $this->assertEqual(count($instances), 1, 'There is one deleted instance');
- // Purge the instance.
- field_purge_batch($batch_size);
- // The instance is gone.
- $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
- $this->assertEqual(count($instances), 0, 'The instance is gone');
- // The field still exists, not deleted, because it has a second instance.
- $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
- $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
- }
- /**
- * Verify that fields are preserved and purged correctly as multiple
- * instances are deleted and purged.
- */
- function testPurgeField() {
- // Start recording hook invocations.
- field_test_memorize();
- $field = reset($this->fields);
- // Delete the first instance.
- $bundle = reset($this->bundles);
- $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
- field_delete_instance($instance);
- // Assert that hook_field_delete() was not called yet.
- $mem = field_test_memorize();
- $this->assertEqual(count($mem), 0, 'No field hooks were called.');
- // Purge the data.
- field_purge_batch(10);
- // Check hooks invocations.
- // - hook_field_load() (multiple hook) should have been called once, for all
- // entities in the bundle.
- // - hook_field_delete() should have been called once for each entity in the
- // bundle.
- $actual_hooks = field_test_memorize();
- $hooks = array();
- $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
- $hooks['field_test_field_load'][] = $stubs;
- foreach ($stubs as $stub) {
- $hooks['field_test_field_delete'][] = $stub;
- }
- $this->checkHooksInvocations($hooks, $actual_hooks);
- // Purge again to purge the instance.
- field_purge_batch(0);
- // The field still exists, not deleted.
- $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
- $this->assertTrue(isset($fields[$field['id']]) && !$fields[$field['id']]['deleted'], 'The field exists and is not deleted');
- // Delete the second instance.
- $bundle = next($this->bundles);
- $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
- field_delete_instance($instance);
- // Assert that hook_field_delete() was not called yet.
- $mem = field_test_memorize();
- $this->assertEqual(count($mem), 0, 'No field hooks were called.');
- // Purge the data.
- field_purge_batch(10);
- // Check hooks invocations (same as above, for the 2nd bundle).
- $actual_hooks = field_test_memorize();
- $hooks = array();
- $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
- $hooks['field_test_field_load'][] = $stubs;
- foreach ($stubs as $stub) {
- $hooks['field_test_field_delete'][] = $stub;
- }
- $this->checkHooksInvocations($hooks, $actual_hooks);
- // The field still exists, deleted.
- $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
- $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');
- // Purge again to purge the instance and the field.
- field_purge_batch(0);
- // The field is gone.
- $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
- $this->assertEqual(count($fields), 0, 'The field is purged.');
- }
- }
- /**
- * Tests entity properties.
- */
- class EntityPropertiesTestCase extends FieldTestCase {
- public static function getInfo() {
- return array(
- 'name' => 'Entity properties',
- 'description' => 'Tests entity properties.',
- 'group' => 'Entity API',
- );
- }
- function setUp() {
- parent::setUp('field_test');
- }
- /**
- * Tests label key and label callback of an entity.
- */
- function testEntityLabel() {
- $entity_types = array(
- 'test_entity_no_label',
- 'test_entity_label',
- 'test_entity_label_callback',
- );
- $entity = field_test_create_stub_entity();
- foreach ($entity_types as $entity_type) {
- $label = entity_label($entity_type, $entity);
- switch ($entity_type) {
- case 'test_entity_no_label':
- $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
- break;
- case 'test_entity_label':
- $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
- break;
- case 'test_entity_label_callback':
- $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
- break;
- }
- }
- }
- }
|