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