Projet

Général

Profil

Paste
Télécharger (164 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / field / tests / field.test @ 76597ebf

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);
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
    $array = array();
2215
    foreach ($this->values as $delta => $value) {
2216
      $array[] = $delta . ':' . $value['value'];
2217
    }
2218
    $this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
2219

    
2220
    // Check the prepare_view steps are invoked.
2221
    $display = array(
2222
      'label' => 'hidden',
2223
      'type' => 'field_test_with_prepare_view',
2224
      'settings' => array(
2225
        'test_formatter_setting_additional' => $this->randomName(),
2226
      ),
2227
    );
2228
    $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
2229
    $view = drupal_render($output);
2230
    $this->drupalSetContent($view);
2231
    $setting = $display['settings']['test_formatter_setting_additional'];
2232
    $this->assertNoText($this->label, 'Label was not displayed.');
2233
    $this->assertNoText('field_test_field_attach_view_alter', 'Alter not fired.');
2234
    foreach ($this->values as $delta => $value) {
2235
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2236
    }
2237

    
2238
    // View mode: check that display settings specified in the instance are
2239
    // used.
2240
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
2241
    $this->drupalSetContent(drupal_render($output));
2242
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
2243
    $this->assertText($this->label, 'Label was displayed.');
2244
    foreach ($this->values as $delta => $value) {
2245
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2246
    }
2247

    
2248
    // Unknown view mode: check that display settings for 'default' view mode
2249
    // are used.
2250
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
2251
    $this->drupalSetContent(drupal_render($output));
2252
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
2253
    $this->assertText($this->label, 'Label was displayed.');
2254
    foreach ($this->values as $delta => $value) {
2255
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2256
    }
2257
  }
2258

    
2259
  /**
2260
   * Test the field_view_value() function.
2261
   */
2262
  function testFieldViewValue() {
2263
    // No display settings: check that default display settings are used.
2264
    $settings = field_info_formatter_settings('field_test_default');
2265
    $setting = $settings['test_formatter_setting'];
2266
    foreach ($this->values as $delta => $value) {
2267
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2268
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
2269
      $this->drupalSetContent(drupal_render($output));
2270
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2271
    }
2272

    
2273
    // Check that explicit display settings are used.
2274
    $display = array(
2275
      'type' => 'field_test_multiple',
2276
      'settings' => array(
2277
        'test_formatter_setting_multiple' => $this->randomName(),
2278
      ),
2279
    );
2280
    $setting = $display['settings']['test_formatter_setting_multiple'];
2281
    $array = array();
2282
    foreach ($this->values as $delta => $value) {
2283
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2284
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
2285
      $this->drupalSetContent(drupal_render($output));
2286
      $this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2287
    }
2288

    
2289
    // Check that prepare_view steps are invoked.
2290
    $display = array(
2291
      'type' => 'field_test_with_prepare_view',
2292
      'settings' => array(
2293
        'test_formatter_setting_additional' => $this->randomName(),
2294
      ),
2295
    );
2296
    $setting = $display['settings']['test_formatter_setting_additional'];
2297
    $array = array();
2298
    foreach ($this->values as $delta => $value) {
2299
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2300
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
2301
      $this->drupalSetContent(drupal_render($output));
2302
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2303
    }
2304

    
2305
    // View mode: check that display settings specified in the instance are
2306
    // used.
2307
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
2308
    foreach ($this->values as $delta => $value) {
2309
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2310
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
2311
      $this->drupalSetContent(drupal_render($output));
2312
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2313
    }
2314

    
2315
    // Unknown view mode: check that display settings for 'default' view mode
2316
    // are used.
2317
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
2318
    foreach ($this->values as $delta => $value) {
2319
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2320
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
2321
      $this->drupalSetContent(drupal_render($output));
2322
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2323
    }
2324
  }
2325
}
2326

    
2327
class FieldCrudTestCase extends FieldTestCase {
2328
  public static function getInfo() {
2329
    return array(
2330
      'name' => 'Field CRUD tests',
2331
      'description' => 'Test field create, read, update, and delete.',
2332
      'group' => 'Field API',
2333
    );
2334
  }
2335

    
2336
  function setUp() {
2337
    // field_update_field() tests use number.module
2338
    parent::setUp('field_test', 'number');
2339
  }
2340

    
2341
  // TODO : test creation with
2342
  // - a full fledged $field structure, check that all the values are there
2343
  // - a minimal $field structure, check all default values are set
2344
  // defer actual $field comparison to a helper function, used for the two cases above
2345

    
2346
  /**
2347
   * Test the creation of a field.
2348
   */
2349
  function testCreateField() {
2350
    $field_definition = array(
2351
      'field_name' => 'field_2',
2352
      'type' => 'test_field',
2353
    );
2354
    field_test_memorize();
2355
    $field_definition = field_create_field($field_definition);
2356
    $mem = field_test_memorize();
2357
    $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');
2358

    
2359
    // Read the raw record from the {field_config_instance} table.
2360
    $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
2361
    $record = $result->fetchAssoc();
2362
    $record['data'] = unserialize($record['data']);
2363

    
2364
    // Ensure that basic properties are preserved.
2365
    $this->assertEqual($record['field_name'], $field_definition['field_name'], 'The field name is properly saved.');
2366
    $this->assertEqual($record['type'], $field_definition['type'], 'The field type is properly saved.');
2367

    
2368
    // Ensure that cardinality defaults to 1.
2369
    $this->assertEqual($record['cardinality'], 1, 'Cardinality defaults to 1.');
2370

    
2371
    // Ensure that default settings are present.
2372
    $field_type = field_info_field_types($field_definition['type']);
2373
    $this->assertIdentical($record['data']['settings'], $field_type['settings'], 'Default field settings have been written.');
2374

    
2375
    // Ensure that default storage was set.
2376
    $this->assertEqual($record['storage_type'], variable_get('field_storage_default'), 'The field type is properly saved.');
2377

    
2378
    // Guarantee that the name is unique.
2379
    try {
2380
      field_create_field($field_definition);
2381
      $this->fail(t('Cannot create two fields with the same name.'));
2382
    }
2383
    catch (FieldException $e) {
2384
      $this->pass(t('Cannot create two fields with the same name.'));
2385
    }
2386

    
2387
    // Check that field type is required.
2388
    try {
2389
      $field_definition = array(
2390
        'field_name' => 'field_1',
2391
      );
2392
      field_create_field($field_definition);
2393
      $this->fail(t('Cannot create a field with no type.'));
2394
    }
2395
    catch (FieldException $e) {
2396
      $this->pass(t('Cannot create a field with no type.'));
2397
    }
2398

    
2399
    // Check that field name is required.
2400
    try {
2401
      $field_definition = array(
2402
        'type' => 'test_field'
2403
      );
2404
      field_create_field($field_definition);
2405
      $this->fail(t('Cannot create an unnamed field.'));
2406
    }
2407
    catch (FieldException $e) {
2408
      $this->pass(t('Cannot create an unnamed field.'));
2409
    }
2410

    
2411
    // Check that field name must start with a letter or _.
2412
    try {
2413
      $field_definition = array(
2414
        'field_name' => '2field_2',
2415
        'type' => 'test_field',
2416
      );
2417
      field_create_field($field_definition);
2418
      $this->fail(t('Cannot create a field with a name starting with a digit.'));
2419
    }
2420
    catch (FieldException $e) {
2421
      $this->pass(t('Cannot create a field with a name starting with a digit.'));
2422
    }
2423

    
2424
    // Check that field name must only contain lowercase alphanumeric or _.
2425
    try {
2426
      $field_definition = array(
2427
        'field_name' => 'field#_3',
2428
        'type' => 'test_field',
2429
      );
2430
      field_create_field($field_definition);
2431
      $this->fail(t('Cannot create a field with a name containing an illegal character.'));
2432
    }
2433
    catch (FieldException $e) {
2434
      $this->pass(t('Cannot create a field with a name containing an illegal character.'));
2435
    }
2436

    
2437
    // Check that field name cannot be longer than 32 characters long.
2438
    try {
2439
      $field_definition = array(
2440
        'field_name' => '_12345678901234567890123456789012',
2441
        'type' => 'test_field',
2442
      );
2443
      field_create_field($field_definition);
2444
      $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
2445
    }
2446
    catch (FieldException $e) {
2447
      $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
2448
    }
2449

    
2450
    // Check that field name can not be an entity key.
2451
    // "ftvid" is known as an entity key from the "test_entity" type.
2452
    try {
2453
      $field_definition = array(
2454
        'type' => 'test_field',
2455
        'field_name' => 'ftvid',
2456
      );
2457
      $field = field_create_field($field_definition);
2458
      $this->fail(t('Cannot create a field bearing the name of an entity key.'));
2459
    }
2460
    catch (FieldException $e) {
2461
      $this->pass(t('Cannot create a field bearing the name of an entity key.'));
2462
    }
2463
  }
2464

    
2465
  /**
2466
   * Test failure to create a field.
2467
   */
2468
  function testCreateFieldFail() {
2469
    $field_name = 'duplicate';
2470
    $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
2471
    $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();
2472

    
2473
    // The field does not appear in field_config.
2474
    $count = $query->execute()->fetchField();
2475
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
2476

    
2477
    // Try to create the field.
2478
    try {
2479
      $field = field_create_field($field_definition);
2480
      $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
2481
    }
2482
    catch (Exception $e) {
2483
      $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
2484
    }
2485

    
2486
    // The field does not appear in field_config.
2487
    $count = $query->execute()->fetchField();
2488
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
2489
  }
2490

    
2491
  /**
2492
   * Test reading back a field definition.
2493
   */
2494
  function testReadField() {
2495
    $field_definition = array(
2496
      'field_name' => 'field_1',
2497
      'type' => 'test_field',
2498
    );
2499
    field_create_field($field_definition);
2500

    
2501
    // Read the field back.
2502
    $field = field_read_field($field_definition['field_name']);
2503
    $this->assertTrue($field_definition < $field, 'The field was properly read.');
2504
  }
2505

    
2506
  /**
2507
   * Tests reading field definitions.
2508
   */
2509
  function testReadFields() {
2510
    $field_definition = array(
2511
      'field_name' => 'field_1',
2512
      'type' => 'test_field',
2513
    );
2514
    field_create_field($field_definition);
2515

    
2516
    // Check that 'single column' criteria works.
2517
    $fields = field_read_fields(array('field_name' => $field_definition['field_name']));
2518
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2519

    
2520
    // Check that 'multi column' criteria works.
2521
    $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => $field_definition['type']));
2522
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2523
    $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => 'foo'));
2524
    $this->assertTrue(empty($fields), 'No field was found.');
2525

    
2526
    // Create an instance of the field.
2527
    $instance_definition = array(
2528
      'field_name' => $field_definition['field_name'],
2529
      'entity_type' => 'test_entity',
2530
      'bundle' => 'test_bundle',
2531
    );
2532
    field_create_instance($instance_definition);
2533

    
2534
    // Check that criteria spanning over the field_config_instance table work.
2535
    $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'bundle' => $instance_definition['bundle']));
2536
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2537
    $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'field_name' => $instance_definition['field_name']));
2538
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2539
  }
2540

    
2541
  /**
2542
   * Test creation of indexes on data column.
2543
   */
2544
  function testFieldIndexes() {
2545
    // Check that indexes specified by the field type are used by default.
2546
    $field_definition = array(
2547
      'field_name' => 'field_1',
2548
      'type' => 'test_field',
2549
    );
2550
    field_create_field($field_definition);
2551
    $field = field_read_field($field_definition['field_name']);
2552
    $expected_indexes = array('value' => array('value'));
2553
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field type indexes saved by default');
2554

    
2555
    // Check that indexes specified by the field definition override the field
2556
    // type indexes.
2557
    $field_definition = array(
2558
      'field_name' => 'field_2',
2559
      'type' => 'test_field',
2560
      'indexes' => array(
2561
        'value' => array(),
2562
      ),
2563
    );
2564
    field_create_field($field_definition);
2565
    $field = field_read_field($field_definition['field_name']);
2566
    $expected_indexes = array('value' => array());
2567
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes override field type indexes');
2568

    
2569
    // Check that indexes specified by the field definition add to the field
2570
    // type indexes.
2571
    $field_definition = array(
2572
      'field_name' => 'field_3',
2573
      'type' => 'test_field',
2574
      'indexes' => array(
2575
        'value_2' => array('value'),
2576
      ),
2577
    );
2578
    field_create_field($field_definition);
2579
    $field = field_read_field($field_definition['field_name']);
2580
    $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
2581
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes are merged with field type indexes');
2582
  }
2583

    
2584
  /**
2585
   * Test the deletion of a field.
2586
   */
2587
  function testDeleteField() {
2588
    // TODO: Also test deletion of the data stored in the field ?
2589

    
2590
    // Create two fields (so we can test that only one is deleted).
2591
    $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
2592
    field_create_field($this->field);
2593
    $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
2594
    field_create_field($this->another_field);
2595

    
2596
    // Create instances for each.
2597
    $this->instance_definition = array(
2598
      'field_name' => $this->field['field_name'],
2599
      'entity_type' => 'test_entity',
2600
      'bundle' => 'test_bundle',
2601
      'widget' => array(
2602
        'type' => 'test_field_widget',
2603
      ),
2604
    );
2605
    field_create_instance($this->instance_definition);
2606
    $this->another_instance_definition = $this->instance_definition;
2607
    $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
2608
    field_create_instance($this->another_instance_definition);
2609

    
2610
    // Test that the first field is not deleted, and then delete it.
2611
    $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
2612
    $this->assertTrue(!empty($field) && empty($field['deleted']), 'A new field is not marked for deletion.');
2613
    field_delete_field($this->field['field_name']);
2614

    
2615
    // Make sure that the field is marked as deleted when it is specifically
2616
    // loaded.
2617
    $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
2618
    $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion.');
2619

    
2620
    // Make sure that this field's instance is marked as deleted when it is
2621
    // specifically loaded.
2622
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
2623
    $this->assertTrue(!empty($instance['deleted']), 'An instance for a deleted field is marked for deletion.');
2624

    
2625
    // Try to load the field normally and make sure it does not show up.
2626
    $field = field_read_field($this->field['field_name']);
2627
    $this->assertTrue(empty($field), 'A deleted field is not loaded by default.');
2628

    
2629
    // Try to load the instance normally and make sure it does not show up.
2630
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2631
    $this->assertTrue(empty($instance), 'An instance for a deleted field is not loaded by default.');
2632

    
2633
    // Make sure the other field (and its field instance) are not deleted.
2634
    $another_field = field_read_field($this->another_field['field_name']);
2635
    $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), 'A non-deleted field is not marked for deletion.');
2636
    $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
2637
    $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), 'An instance of a non-deleted field is not marked for deletion.');
2638

    
2639
    // Try to create a new field the same name as a deleted field and
2640
    // write data into it.
2641
    field_create_field($this->field);
2642
    field_create_instance($this->instance_definition);
2643
    $field = field_read_field($this->field['field_name']);
2644
    $this->assertTrue(!empty($field) && empty($field['deleted']), 'A new field with a previously used name is created.');
2645
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2646
    $this->assertTrue(!empty($instance) && empty($instance['deleted']), 'A new instance for a previously used field name is created.');
2647

    
2648
    // Save an entity with data for the field
2649
    $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
2650
    $langcode = LANGUAGE_NONE;
2651
    $values[0]['value'] = mt_rand(1, 127);
2652
    $entity->{$field['field_name']}[$langcode] = $values;
2653
    $entity_type = 'test_entity';
2654
    field_attach_insert('test_entity', $entity);
2655

    
2656
    // Verify the field is present on load
2657
    $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
2658
    field_attach_load($entity_type, array(0 => $entity));
2659
    $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
2660
    foreach ($values as $delta => $value) {
2661
      $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
2662
    }
2663
  }
2664

    
2665
  function testUpdateNonExistentField() {
2666
    $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
2667
    try {
2668
      field_update_field($test_field);
2669
      $this->fail(t('Cannot update a field that does not exist.'));
2670
    }
2671
    catch (FieldException $e) {
2672
      $this->pass(t('Cannot update a field that does not exist.'));
2673
    }
2674
  }
2675

    
2676
  function testUpdateFieldType() {
2677
    $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
2678
    $field = field_create_field($field);
2679

    
2680
    $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
2681
    try {
2682
      field_update_field($test_field);
2683
      $this->fail(t('Cannot update a field to a different type.'));
2684
    }
2685
    catch (FieldException $e) {
2686
      $this->pass(t('Cannot update a field to a different type.'));
2687
    }
2688
  }
2689

    
2690
  /**
2691
   * Test updating a field.
2692
   */
2693
  function testUpdateField() {
2694
    // Create a field with a defined cardinality, so that we can ensure it's
2695
    // respected. Since cardinality enforcement is consistent across database
2696
    // systems, it makes a good test case.
2697
    $cardinality = 4;
2698
    $field_definition = array(
2699
      'field_name' => 'field_update',
2700
      'type' => 'test_field',
2701
      'cardinality' => $cardinality,
2702
    );
2703
    $field_definition = field_create_field($field_definition);
2704
    $instance = array(
2705
      'field_name' => 'field_update',
2706
      'entity_type' => 'test_entity',
2707
      'bundle' => 'test_bundle',
2708
    );
2709
    $instance = field_create_instance($instance);
2710

    
2711
    do {
2712
      // We need a unique ID for our entity. $cardinality will do.
2713
      $id = $cardinality;
2714
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
2715
      // Fill in the entity with more values than $cardinality.
2716
      for ($i = 0; $i < 20; $i++) {
2717
        $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
2718
      }
2719
      // Save the entity.
2720
      field_attach_insert('test_entity', $entity);
2721
      // Load back and assert there are $cardinality number of values.
2722
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
2723
      field_attach_load('test_entity', array($id => $entity));
2724
      $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
2725
      // Now check the values themselves.
2726
      for ($delta = 0; $delta < $cardinality; $delta++) {
2727
        $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
2728
      }
2729
      // Increase $cardinality and set the field cardinality to the new value.
2730
      $field_definition['cardinality'] = ++$cardinality;
2731
      field_update_field($field_definition);
2732
    } while ($cardinality < 6);
2733
  }
2734

    
2735
  /**
2736
   * Test field type modules forbidding an update.
2737
   */
2738
  function testUpdateFieldForbid() {
2739
    $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
2740
    $field = field_create_field($field);
2741
    $field['settings']['changeable']++;
2742
    try {
2743
      field_update_field($field);
2744
      $this->pass(t("A changeable setting can be updated."));
2745
    }
2746
    catch (FieldException $e) {
2747
      $this->fail(t("An unchangeable setting cannot be updated."));
2748
    }
2749
    $field['settings']['unchangeable']++;
2750
    try {
2751
      field_update_field($field);
2752
      $this->fail(t("An unchangeable setting can be updated."));
2753
    }
2754
    catch (FieldException $e) {
2755
      $this->pass(t("An unchangeable setting cannot be updated."));
2756
    }
2757
  }
2758

    
2759
  /**
2760
   * Test that fields are properly marked active or inactive.
2761
   */
2762
  function testActive() {
2763
    $field_definition = array(
2764
      'field_name' => 'field_1',
2765
      'type' => 'test_field',
2766
      // For this test, we need a storage backend provided by a different
2767
      // module than field_test.module.
2768
      'storage' => array(
2769
        'type' => 'field_sql_storage',
2770
      ),
2771
    );
2772
    field_create_field($field_definition);
2773

    
2774
    // Test disabling and enabling:
2775
    // - the field type module,
2776
    // - the storage module,
2777
    // - both.
2778
    $this->_testActiveHelper($field_definition, array('field_test'));
2779
    $this->_testActiveHelper($field_definition, array('field_sql_storage'));
2780
    $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
2781
  }
2782

    
2783
  /**
2784
   * Helper function for testActive().
2785
   *
2786
   * Test dependency between a field and a set of modules.
2787
   *
2788
   * @param $field_definition
2789
   *   A field definition.
2790
   * @param $modules
2791
   *   An aray of module names. The field will be tested to be inactive as long
2792
   *   as any of those modules is disabled.
2793
   */
2794
  function _testActiveHelper($field_definition, $modules) {
2795
    $field_name = $field_definition['field_name'];
2796

    
2797
    // Read the field.
2798
    $field = field_read_field($field_name);
2799
    $this->assertTrue($field_definition <= $field, 'The field was properly read.');
2800

    
2801
    module_disable($modules, FALSE);
2802

    
2803
    $fields = field_read_fields(array('field_name' => $field_name), array('include_inactive' => TRUE));
2804
    $this->assertTrue(isset($fields[$field_name]) && $field_definition < $field, 'The field is properly read when explicitly fetching inactive fields.');
2805

    
2806
    // Re-enable modules one by one, and check that the field is still inactive
2807
    // while some modules remain disabled.
2808
    while ($modules) {
2809
      $field = field_read_field($field_name);
2810
      $this->assertTrue(empty($field), format_string('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));
2811

    
2812
      $module = array_shift($modules);
2813
      module_enable(array($module), FALSE);
2814
    }
2815

    
2816
    // Check that the field is active again after all modules have been
2817
    // enabled.
2818
    $field = field_read_field($field_name);
2819
    $this->assertTrue($field_definition <= $field, 'The field was was marked active.');
2820
  }
2821
}
2822

    
2823
class FieldInstanceCrudTestCase extends FieldTestCase {
2824
  protected $field;
2825

    
2826
  public static function getInfo() {
2827
    return array(
2828
      'name' => 'Field instance CRUD tests',
2829
      'description' => 'Create field entities by attaching fields to entities.',
2830
      'group' => 'Field API',
2831
    );
2832
  }
2833

    
2834
  function setUp() {
2835
    parent::setUp('field_test');
2836

    
2837
    $this->field = array(
2838
      'field_name' => drupal_strtolower($this->randomName()),
2839
      'type' => 'test_field',
2840
    );
2841
    field_create_field($this->field);
2842
    $this->instance_definition = array(
2843
      'field_name' => $this->field['field_name'],
2844
      'entity_type' => 'test_entity',
2845
      'bundle' => 'test_bundle',
2846
    );
2847
  }
2848

    
2849
  // TODO : test creation with
2850
  // - a full fledged $instance structure, check that all the values are there
2851
  // - a minimal $instance structure, check all default values are set
2852
  // defer actual $instance comparison to a helper function, used for the two cases above,
2853
  // and for testUpdateFieldInstance
2854

    
2855
  /**
2856
   * Test the creation of a field instance.
2857
   */
2858
  function testCreateFieldInstance() {
2859
    field_create_instance($this->instance_definition);
2860

    
2861
    // Read the raw record from the {field_config_instance} table.
2862
    $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']));
2863
    $record = $result->fetchAssoc();
2864
    $record['data'] = unserialize($record['data']);
2865

    
2866
    $field_type = field_info_field_types($this->field['type']);
2867
    $widget_type = field_info_widget_types($field_type['default_widget']);
2868
    $formatter_type = field_info_formatter_types($field_type['default_formatter']);
2869

    
2870
    // Check that default values are set.
2871
    $this->assertIdentical($record['data']['required'], FALSE, 'Required defaults to false.');
2872
    $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], 'Label defaults to field name.');
2873
    $this->assertIdentical($record['data']['description'], '', 'Description defaults to empty string.');
2874
    $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], 'Default widget has been written.');
2875
    $this->assertTrue(isset($record['data']['display']['default']), 'Display for "full" view_mode has been written.');
2876
    $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], 'Default formatter for "full" view_mode has been written.');
2877

    
2878
    // Check that default settings are set.
2879
    $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , 'Default instance settings have been written.');
2880
    $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , 'Default widget settings have been written.');
2881
    $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], 'Default formatter settings for "full" view_mode have been written.');
2882

    
2883
    // Guarantee that the field/bundle combination is unique.
2884
    try {
2885
      field_create_instance($this->instance_definition);
2886
      $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
2887
    }
2888
    catch (FieldException $e) {
2889
      $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
2890
    }
2891

    
2892
    // Check that the specified field exists.
2893
    try {
2894
      $this->instance_definition['field_name'] = $this->randomName();
2895
      field_create_instance($this->instance_definition);
2896
      $this->fail(t('Cannot create an instance of a non-existing field.'));
2897
    }
2898
    catch (FieldException $e) {
2899
      $this->pass(t('Cannot create an instance of a non-existing field.'));
2900
    }
2901

    
2902
    // Create a field restricted to a specific entity type.
2903
    $field_restricted = array(
2904
      'field_name' => drupal_strtolower($this->randomName()),
2905
      'type' => 'test_field',
2906
      'entity_types' => array('test_cacheable_entity'),
2907
    );
2908
    field_create_field($field_restricted);
2909

    
2910
    // Check that an instance can be added to an entity type allowed
2911
    // by the field.
2912
    try {
2913
      $instance = $this->instance_definition;
2914
      $instance['field_name'] = $field_restricted['field_name'];
2915
      $instance['entity_type'] = 'test_cacheable_entity';
2916
      field_create_instance($instance);
2917
      $this->pass(t('Can create an instance on an entity type allowed by the field.'));
2918
    }
2919
    catch (FieldException $e) {
2920
      $this->fail(t('Can create an instance on an entity type allowed by the field.'));
2921
    }
2922

    
2923
    // Check that an instance cannot be added to an entity type
2924
    // forbidden by the field.
2925
    try {
2926
      $instance = $this->instance_definition;
2927
      $instance['field_name'] = $field_restricted['field_name'];
2928
      field_create_instance($instance);
2929
      $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
2930
    }
2931
    catch (FieldException $e) {
2932
      $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
2933
    }
2934

    
2935
    // TODO: test other failures.
2936
  }
2937

    
2938
  /**
2939
   * Test reading back an instance definition.
2940
   */
2941
  function testReadFieldInstance() {
2942
    field_create_instance($this->instance_definition);
2943

    
2944
    // Read the instance back.
2945
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2946
    $this->assertTrue($this->instance_definition < $instance, 'The field was properly read.');
2947
  }
2948

    
2949
  /**
2950
   * Test the update of a field instance.
2951
   */
2952
  function testUpdateFieldInstance() {
2953
    field_create_instance($this->instance_definition);
2954
    $field_type = field_info_field_types($this->field['type']);
2955

    
2956
    // Check that basic changes are saved.
2957
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2958
    $instance['required'] = !$instance['required'];
2959
    $instance['label'] = $this->randomName();
2960
    $instance['description'] = $this->randomName();
2961
    $instance['settings']['test_instance_setting'] = $this->randomName();
2962
    $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
2963
    $instance['widget']['weight']++;
2964
    $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
2965
    $instance['display']['default']['weight']++;
2966
    field_update_instance($instance);
2967

    
2968
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2969
    $this->assertEqual($instance['required'], $instance_new['required'], '"required" change is saved');
2970
    $this->assertEqual($instance['label'], $instance_new['label'], '"label" change is saved');
2971
    $this->assertEqual($instance['description'], $instance_new['description'], '"description" change is saved');
2972
    $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], 'Widget setting change is saved');
2973
    $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], 'Widget weight change is saved');
2974
    $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], 'Formatter setting change is saved');
2975
    $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], 'Widget weight change is saved');
2976

    
2977
    // Check that changing widget and formatter types updates the default settings.
2978
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2979
    $instance['widget']['type'] = 'test_field_widget_multiple';
2980
    $instance['display']['default']['type'] = 'field_test_multiple';
2981
    field_update_instance($instance);
2982

    
2983
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2984
    $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , 'Widget type change is saved.');
2985
    $settings = field_info_widget_settings($instance_new['widget']['type']);
2986
    $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , 'Widget type change updates default settings.');
2987
    $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , 'Formatter type change is saved.');
2988
    $info = field_info_formatter_types($instance_new['display']['default']['type']);
2989
    $settings = $info['settings'];
2990
    $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , 'Changing formatter type updates default settings.');
2991

    
2992
    // Check that adding a new view mode is saved and gets default settings.
2993
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2994
    $instance['display']['teaser'] = array();
2995
    field_update_instance($instance);
2996

    
2997
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2998
    $this->assertTrue(isset($instance_new['display']['teaser']), 'Display for the new view_mode has been written.');
2999
    $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], 'Default formatter for the new view_mode has been written.');
3000
    $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
3001
    $settings = $info['settings'];
3002
    $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , 'Default formatter settings for the new view_mode have been written.');
3003

    
3004
    // TODO: test failures.
3005
  }
3006

    
3007
  /**
3008
   * Test the deletion of a field instance.
3009
   */
3010
  function testDeleteFieldInstance() {
3011
    // TODO: Test deletion of the data stored in the field also.
3012
    // Need to check that data for a 'deleted' field / instance doesn't get loaded
3013
    // Need to check data marked deleted is cleaned on cron (not implemented yet...)
3014

    
3015
    // Create two instances for the same field so we can test that only one
3016
    // is deleted.
3017
    field_create_instance($this->instance_definition);
3018
    $this->another_instance_definition = $this->instance_definition;
3019
    $this->another_instance_definition['bundle'] .= '_another_bundle';
3020
    $instance = field_create_instance($this->another_instance_definition);
3021

    
3022
    // Test that the first instance is not deleted, and then delete it.
3023
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
3024
    $this->assertTrue(!empty($instance) && empty($instance['deleted']), 'A new field instance is not marked for deletion.');
3025
    field_delete_instance($instance);
3026

    
3027
    // Make sure the instance is marked as deleted when the instance is
3028
    // specifically loaded.
3029
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle'], array('include_deleted' => TRUE));
3030
    $this->assertTrue(!empty($instance['deleted']), 'A deleted field instance is marked for deletion.');
3031

    
3032
    // Try to load the instance normally and make sure it does not show up.
3033
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
3034
    $this->assertTrue(empty($instance), 'A deleted field instance is not loaded by default.');
3035

    
3036
    // Make sure the other field instance is not deleted.
3037
    $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
3038
    $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), 'A non-deleted field instance is not marked for deletion.');
3039

    
3040
    // Make sure the field is deleted when its last instance is deleted.
3041
    field_delete_instance($another_instance);
3042
    $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
3043
    $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion after all its instances have been marked for deletion.');
3044
  }
3045
}
3046

    
3047
/**
3048
 * Unit test class for the multilanguage fields logic.
3049
 *
3050
 * The following tests will check the multilanguage logic of _field_invoke() and
3051
 * that only the correct values are returned by field_available_languages().
3052
 */
3053
class FieldTranslationsTestCase extends FieldTestCase {
3054
  public static function getInfo() {
3055
    return array(
3056
      'name' => 'Field translations tests',
3057
      'description' => 'Test multilanguage fields logic.',
3058
      'group' => 'Field API',
3059
    );
3060
  }
3061

    
3062
  function setUp() {
3063
    parent::setUp('locale', 'field_test');
3064

    
3065
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
3066

    
3067
    $this->entity_type = 'test_entity';
3068

    
3069
    $field = array(
3070
      'field_name' => $this->field_name,
3071
      'type' => 'test_field',
3072
      'cardinality' => 4,
3073
      'translatable' => TRUE,
3074
    );
3075
    field_create_field($field);
3076
    $this->field = field_read_field($this->field_name);
3077

    
3078
    $instance = array(
3079
      'field_name' => $this->field_name,
3080
      'entity_type' => $this->entity_type,
3081
      'bundle' => 'test_bundle',
3082
    );
3083
    field_create_instance($instance);
3084
    $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');
3085

    
3086
    require_once DRUPAL_ROOT . '/includes/locale.inc';
3087
    for ($i = 0; $i < 3; ++$i) {
3088
      locale_add_language('l' . $i, $this->randomString(), $this->randomString());
3089
    }
3090
  }
3091

    
3092
  /**
3093
   * Ensures that only valid values are returned by field_available_languages().
3094
   */
3095
  function testFieldAvailableLanguages() {
3096
    // Test 'translatable' fieldable info.
3097
    field_test_entity_info_translatable('test_entity', FALSE);
3098
    $field = $this->field;
3099
    $field['field_name'] .= '_untranslatable';
3100

    
3101
    // Enable field translations for the entity.
3102
    field_test_entity_info_translatable('test_entity', TRUE);
3103

    
3104
    // Test hook_field_languages() invocation on a translatable field.
3105
    variable_set('field_test_field_available_languages_alter', TRUE);
3106
    $enabled_languages = field_content_languages();
3107
    $available_languages = field_available_languages($this->entity_type, $this->field);
3108
    foreach ($available_languages as $delta => $langcode) {
3109
      if ($langcode != 'xx' && $langcode != 'en') {
3110
        $this->assertTrue(in_array($langcode, $enabled_languages), format_string('%language is an enabled language.', array('%language' => $langcode)));
3111
      }
3112
    }
3113
    $this->assertTrue(in_array('xx', $available_languages), format_string('%language was made available.', array('%language' => 'xx')));
3114
    $this->assertFalse(in_array('en', $available_languages), format_string('%language was made unavailable.', array('%language' => 'en')));
3115

    
3116
    // Test field_available_languages() behavior for untranslatable fields.
3117
    $this->field['translatable'] = FALSE;
3118
    field_update_field($this->field);
3119
    $available_languages = field_available_languages($this->entity_type, $this->field);
3120
    $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, 'For untranslatable fields only LANGUAGE_NONE is available.');
3121
  }
3122

    
3123
  /**
3124
   * Test the multilanguage logic of _field_invoke().
3125
   */
3126
  function testFieldInvoke() {
3127
    // Enable field translations for the entity.
3128
    field_test_entity_info_translatable('test_entity', TRUE);
3129

    
3130
    $entity_type = 'test_entity';
3131
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
3132

    
3133
    // Populate some extra languages to check if _field_invoke() correctly uses
3134
    // the result of field_available_languages().
3135
    $values = array();
3136
    $extra_languages = mt_rand(1, 4);
3137
    $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
3138
    for ($i = 0; $i < $extra_languages; ++$i) {
3139
      $languages[] = $this->randomName(2);
3140
    }
3141

    
3142
    // For each given language provide some random values.
3143
    foreach ($languages as $langcode) {
3144
      for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
3145
        $values[$langcode][$delta]['value'] = mt_rand(1, 127);
3146
      }
3147
    }
3148
    $entity->{$this->field_name} = $values;
3149

    
3150
    $results = _field_invoke('test_op', $entity_type, $entity);
3151
    foreach ($results as $langcode => $result) {
3152
      $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
3153
      // Check whether the parameters passed to _field_invoke() were correctly
3154
      // forwarded to the callback function.
3155
      $this->assertEqual($hash, $result, format_string('The result for %language is correctly stored.', array('%language' => $langcode)));
3156
    }
3157

    
3158
    $this->assertEqual(count($results), count($available_languages), 'No unavailable language has been processed.');
3159
  }
3160

    
3161
  /**
3162
   * Test the multilanguage logic of _field_invoke_multiple().
3163
   */
3164
  function testFieldInvokeMultiple() {
3165
    // Enable field translations for the entity.
3166
    field_test_entity_info_translatable('test_entity', TRUE);
3167

    
3168
    $values = array();
3169
    $options = array();
3170
    $entities = array();
3171
    $entity_type = 'test_entity';
3172
    $entity_count = 5;
3173
    $available_languages = field_available_languages($this->entity_type, $this->field);
3174

    
3175
    for ($id = 1; $id <= $entity_count; ++$id) {
3176
      $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
3177
      $languages = $available_languages;
3178

    
3179
      // Populate some extra languages to check whether _field_invoke()
3180
      // correctly uses the result of field_available_languages().
3181
      $extra_languages = mt_rand(1, 4);
3182
      for ($i = 0; $i < $extra_languages; ++$i) {
3183
        $languages[] = $this->randomName(2);
3184
      }
3185

    
3186
      // For each given language provide some random values.
3187
      $language_count = count($languages);
3188
      for ($i = 0; $i < $language_count; ++$i) {
3189
        $langcode = $languages[$i];
3190
        // Avoid to populate at least one field translation to check that
3191
        // per-entity language suggestions work even when available field values
3192
        // are different for each language.
3193
        if ($i !== $id) {
3194
          for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
3195
            $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
3196
          }
3197
        }
3198
        // Ensure that a language for which there is no field translation is
3199
        // used as display language to prepare per-entity language suggestions.
3200
        elseif (!isset($display_language)) {
3201
          $display_language = $langcode;
3202
        }
3203
      }
3204

    
3205
      $entity->{$this->field_name} = $values[$id];
3206
      $entities[$id] = $entity;
3207

    
3208
      // Store per-entity language suggestions.
3209
      $options['language'][$id] = field_language($entity_type, $entity, NULL, $display_language);
3210
    }
3211

    
3212
    $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
3213
    foreach ($grouped_results as $id => $results) {
3214
      foreach ($results as $langcode => $result) {
3215
        if (isset($values[$id][$langcode])) {
3216
          $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
3217
          // Check whether the parameters passed to _field_invoke_multiple()
3218
          // were correctly forwarded to the callback function.
3219
          $this->assertEqual($hash, $result, format_string('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
3220
        }
3221
      }
3222
      $this->assertEqual(count($results), count($available_languages), format_string('No unavailable language has been processed for entity %id.', array('%id' => $id)));
3223
    }
3224

    
3225
    $null = NULL;
3226
    $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities, $null, $null, $options);
3227
    foreach ($grouped_results as $id => $results) {
3228
      foreach ($results as $langcode => $result) {
3229
        $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)));
3230
      }
3231
    }
3232
  }
3233

    
3234
  /**
3235
   * Test translatable fields storage/retrieval.
3236
   */
3237
  function testTranslatableFieldSaveLoad() {
3238
    // Enable field translations for nodes.
3239
    field_test_entity_info_translatable('node', TRUE);
3240
    $entity_info = entity_get_info('node');
3241
    $this->assertTrue(count($entity_info['translation']), 'Nodes are translatable.');
3242

    
3243
    // Prepare the field translations.
3244
    field_test_entity_info_translatable('test_entity', TRUE);
3245
    $eid = $evid = 1;
3246
    $entity_type = 'test_entity';
3247
    $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
3248
    $field_translations = array();
3249
    $available_languages = field_available_languages($entity_type, $this->field);
3250
    $this->assertTrue(count($available_languages) > 1, 'Field is translatable.');
3251
    foreach ($available_languages as $langcode) {
3252
      $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
3253
    }
3254

    
3255
    // Save and reload the field translations.
3256
    $entity->{$this->field_name} = $field_translations;
3257
    field_attach_insert($entity_type, $entity);
3258
    unset($entity->{$this->field_name});
3259
    field_attach_load($entity_type, array($eid => $entity));
3260

    
3261
    // Check if the correct values were saved/loaded.
3262
    foreach ($field_translations as $langcode => $items) {
3263
      $result = TRUE;
3264
      foreach ($items as $delta => $item) {
3265
        $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
3266
      }
3267
      $this->assertTrue($result, format_string('%language translation correctly handled.', array('%language' => $langcode)));
3268
    }
3269
  }
3270

    
3271
  /**
3272
   * Tests display language logic for translatable fields.
3273
   */
3274
  function testFieldDisplayLanguage() {
3275
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
3276
    $entity_type = 'test_entity';
3277

    
3278
    // We need an additional field here to properly test display language
3279
    // suggestions.
3280
    $field = array(
3281
      'field_name' => $field_name,
3282
      'type' => 'test_field',
3283
      'cardinality' => 2,
3284
      'translatable' => TRUE,
3285
    );
3286
    field_create_field($field);
3287

    
3288
    $instance = array(
3289
      'field_name' => $field['field_name'],
3290
      'entity_type' => $entity_type,
3291
      'bundle' => 'test_bundle',
3292
    );
3293
    field_create_instance($instance);
3294

    
3295
    $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
3296
    $instances = field_info_instances($entity_type, $this->instance['bundle']);
3297

    
3298
    $enabled_languages = field_content_languages();
3299
    $languages = array();
3300

    
3301
    // Generate field translations for languages different from the first
3302
    // enabled.
3303
    foreach ($instances as $instance) {
3304
      $field_name = $instance['field_name'];
3305
      $field = field_info_field($field_name);
3306
      do {
3307
        // Index 0 is reserved for the requested language, this way we ensure
3308
        // that no field is actually populated with it.
3309
        $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
3310
      }
3311
      while (isset($languages[$langcode]));
3312
      $languages[$langcode] = TRUE;
3313
      $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
3314
    }
3315

    
3316
    // Test multiple-fields display languages for untranslatable entities.
3317
    field_test_entity_info_translatable($entity_type, FALSE);
3318
    drupal_static_reset('field_language');
3319
    $requested_language = $enabled_languages[0];
3320
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);
3321
    foreach ($instances as $instance) {
3322
      $field_name = $instance['field_name'];
3323
      $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)));
3324
    }
3325

    
3326
    // Test multiple-fields display languages for translatable entities.
3327
    field_test_entity_info_translatable($entity_type, TRUE);
3328
    drupal_static_reset('field_language');
3329
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);
3330

    
3331
    foreach ($instances as $instance) {
3332
      $field_name = $instance['field_name'];
3333
      $langcode = $display_language[$field_name];
3334
      // As the requested language was not assinged to any field, if the
3335
      // returned language is defined for the current field, core fallback rules
3336
      // were successfully applied.
3337
      $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)));
3338
    }
3339

    
3340
    // Test single-field display language.
3341
    drupal_static_reset('field_language');
3342
    $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
3343
    $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)));
3344

    
3345
    // Test field_language() basic behavior without language fallback.
3346
    variable_set('field_test_language_fallback', FALSE);
3347
    $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
3348
    drupal_static_reset('field_language');
3349
    $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
3350
    $this->assertEqual($display_language, $requested_language, 'Display language behave correctly when language fallback is disabled');
3351
  }
3352

    
3353
  /**
3354
   * Tests field translations when creating a new revision.
3355
   */
3356
  function testFieldFormTranslationRevisions() {
3357
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
3358
    $this->drupalLogin($web_user);
3359

    
3360
    // Prepare the field translations.
3361
    field_test_entity_info_translatable($this->entity_type, TRUE);
3362
    $eid = 1;
3363
    $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
3364
    $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
3365
    unset($available_languages[LANGUAGE_NONE]);
3366
    $field_name = $this->field['field_name'];
3367

    
3368
    // Store the field translations.
3369
    $entity->is_new = TRUE;
3370
    foreach ($available_languages as $langcode => $value) {
3371
      $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
3372
    }
3373
    field_test_entity_save($entity);
3374

    
3375
    // Create a new revision.
3376
    $langcode = field_valid_language(NULL);
3377
    $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
3378
    $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));
3379

    
3380
    // Check translation revisions.
3381
    $this->checkTranslationRevisions($eid, $eid, $available_languages);
3382
    $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
3383
  }
3384

    
3385
  /**
3386
   * Check if the field translation attached to the entity revision identified
3387
   * by the passed arguments were correctly stored.
3388
   */
3389
  private function checkTranslationRevisions($eid, $evid, $available_languages) {
3390
    $field_name = $this->field['field_name'];
3391
    $entity = field_test_entity_test_load($eid, $evid);
3392
    foreach ($available_languages as $langcode => $value) {
3393
      $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
3394
      $this->assertTrue($passed, format_string('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
3395
    }
3396
  }
3397
}
3398

    
3399
/**
3400
 * Unit test class for field bulk delete and batch purge functionality.
3401
 */
3402
class FieldBulkDeleteTestCase extends FieldTestCase {
3403
  protected $field;
3404

    
3405
  public static function getInfo() {
3406
    return array(
3407
      'name' => 'Field bulk delete tests',
3408
      'description' => 'Bulk delete fields and instances, and clean up afterwards.',
3409
      'group' => 'Field API',
3410
    );
3411
  }
3412

    
3413
  /**
3414
   * Convenience function for Field API tests.
3415
   *
3416
   * Given an array of potentially fully-populated entities and an
3417
   * optional field name, generate an array of stub entities of the
3418
   * same fieldable type which contains the data for the field name
3419
   * (if given).
3420
   *
3421
   * @param $entity_type
3422
   *   The entity type of $entities.
3423
   * @param $entities
3424
   *   An array of entities of type $entity_type.
3425
   * @param $field_name
3426
   *   Optional; a field name whose data should be copied from
3427
   *   $entities into the returned stub entities.
3428
   * @return
3429
   *   An array of stub entities corresponding to $entities.
3430
   */
3431
  function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
3432
    $stubs = array();
3433
    foreach ($entities as $id => $entity) {
3434
      $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
3435
      if (isset($field_name)) {
3436
        $stub->{$field_name} = $entity->{$field_name};
3437
      }
3438
      $stubs[$id] = $stub;
3439
    }
3440
    return $stubs;
3441
  }
3442

    
3443
  /**
3444
   * Tests that the expected hooks have been invoked on the expected entities.
3445
   *
3446
   * @param $expected_hooks
3447
   *   An array keyed by hook name, with one entry per expected invocation.
3448
   *   Each entry is the value of the "$entity" parameter the hook is expected
3449
   *   to have been passed.
3450
   * @param $actual_hooks
3451
   *   The array of actual hook invocations recorded by field_test_memorize().
3452
   */
3453
  function checkHooksInvocations($expected_hooks, $actual_hooks) {
3454
    foreach ($expected_hooks as $hook => $invocations) {
3455
      $actual_invocations = $actual_hooks[$hook];
3456

    
3457
      // Check that the number of invocations is correct.
3458
      $this->assertEqual(count($actual_invocations), count($invocations), "$hook() was called the expected number of times.");
3459

    
3460
      // Check that the hook was called for each expected argument.
3461
      foreach ($invocations as $argument) {
3462
        $found = FALSE;
3463
        foreach ($actual_invocations as $actual_arguments) {
3464
          if ($actual_arguments[1] == $argument) {
3465
            $found = TRUE;
3466
            break;
3467
          }
3468
        }
3469
        $this->assertTrue($found, "$hook() was called on expected argument");
3470
      }
3471
    }
3472
  }
3473

    
3474
  function setUp() {
3475
    parent::setUp('field_test');
3476

    
3477
    $this->fields = array();
3478
    $this->instances = array();
3479
    $this->entities = array();
3480
    $this->entities_by_bundles = array();
3481

    
3482
    // Create two bundles.
3483
    $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
3484
    foreach ($this->bundles as $name => $desc) {
3485
      field_test_create_bundle($name, $desc);
3486
    }
3487

    
3488
    // Create two fields.
3489
    $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
3490
    $this->fields[] = field_create_field($field);
3491
    $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
3492
    $this->fields[] = field_create_field($field);
3493

    
3494
    // For each bundle, create an instance of each field, and 10
3495
    // entities with values for each field.
3496
    $id = 0;
3497
    $this->entity_type = 'test_entity';
3498
    foreach ($this->bundles as $bundle) {
3499
      foreach ($this->fields as $field) {
3500
        $instance = array(
3501
          'field_name' => $field['field_name'],
3502
          'entity_type' => $this->entity_type,
3503
          'bundle' => $bundle,
3504
          'widget' => array(
3505
            'type' => 'test_field_widget',
3506
          )
3507
        );
3508
        $this->instances[] = field_create_instance($instance);
3509
      }
3510

    
3511
      for ($i = 0; $i < 10; $i++) {
3512
        $entity = field_test_create_stub_entity($id, $id, $bundle);
3513
        foreach ($this->fields as $field) {
3514
          $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
3515
        }
3516

    
3517
        $this->entities[$id] = $entity;
3518
        // Also keep track of the entities per bundle.
3519
        $this->entities_by_bundles[$bundle][$id] = $entity;
3520
        field_attach_insert($this->entity_type, $entity);
3521
        $id++;
3522
      }
3523
    }
3524
  }
3525

    
3526
  /**
3527
   * Verify that deleting an instance leaves the field data items in
3528
   * the database and that the appropriate Field API functions can
3529
   * operate on the deleted data and instance.
3530
   *
3531
   * This tests how EntityFieldQuery interacts with
3532
   * field_delete_instance() and could be moved to FieldCrudTestCase,
3533
   * but depends on this class's setUp().
3534
   */
3535
  function testDeleteFieldInstance() {
3536
    $bundle = reset($this->bundles);
3537
    $field = reset($this->fields);
3538

    
3539
    // There are 10 entities of this bundle.
3540
    $query = new EntityFieldQuery();
3541
    $found = $query
3542
      ->fieldCondition($field)
3543
      ->entityCondition('bundle', $bundle)
3544
      ->execute();
3545
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');
3546

    
3547
    // Delete the instance.
3548
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3549
    field_delete_instance($instance);
3550

    
3551
    // The instance still exists, deleted.
3552
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
3553
    $this->assertEqual(count($instances), 1, 'There is one deleted instance');
3554
    $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');
3555

    
3556
    // There are 0 entities of this bundle with non-deleted data.
3557
    $query = new EntityFieldQuery();
3558
    $found = $query
3559
      ->fieldCondition($field)
3560
      ->entityCondition('bundle', $bundle)
3561
      ->execute();
3562
    $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');
3563

    
3564
    // There are 10 entities of this bundle when deleted fields are allowed, and
3565
    // their values are correct.
3566
    $query = new EntityFieldQuery();
3567
    $found = $query
3568
      ->fieldCondition($field)
3569
      ->entityCondition('bundle', $bundle)
3570
      ->deleted(TRUE)
3571
      ->execute();
3572
    field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
3573
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
3574
    foreach ($found['test_entity'] as $id => $entity) {
3575
      $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
3576
    }
3577
  }
3578

    
3579
  /**
3580
   * Verify that field data items and instances are purged when an
3581
   * instance is deleted.
3582
   */
3583
  function testPurgeInstance() {
3584
    // Start recording hook invocations.
3585
    field_test_memorize();
3586

    
3587
    $bundle = reset($this->bundles);
3588
    $field = reset($this->fields);
3589

    
3590
    // Delete the instance.
3591
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3592
    field_delete_instance($instance);
3593

    
3594
    // No field hooks were called.
3595
    $mem = field_test_memorize();
3596
    $this->assertEqual(count($mem), 0, 'No field hooks were called');
3597

    
3598
    $batch_size = 2;
3599
    for ($count = 8; $count >= 0; $count -= $batch_size) {
3600
      // Purge two entities.
3601
      field_purge_batch($batch_size);
3602

    
3603
      // There are $count deleted entities left.
3604
      $query = new EntityFieldQuery();
3605
      $found = $query
3606
        ->fieldCondition($field)
3607
        ->entityCondition('bundle', $bundle)
3608
        ->deleted(TRUE)
3609
        ->execute();
3610
      $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
3611
    }
3612

    
3613
    // Check hooks invocations.
3614
    // - hook_field_load() (multiple hook) should have been called on all
3615
    // entities by pairs of two.
3616
    // - hook_field_delete() should have been called once for each entity in the
3617
    // bundle.
3618
    $actual_hooks = field_test_memorize();
3619
    $hooks = array();
3620
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3621
    foreach (array_chunk($stubs, $batch_size, TRUE) as $chunk) {
3622
      $hooks['field_test_field_load'][] = $chunk;
3623
    }
3624
    foreach ($stubs as $stub) {
3625
      $hooks['field_test_field_delete'][] = $stub;
3626
    }
3627
    $this->checkHooksInvocations($hooks, $actual_hooks);
3628

    
3629
    // The instance still exists, deleted.
3630
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
3631
    $this->assertEqual(count($instances), 1, 'There is one deleted instance');
3632

    
3633
    // Purge the instance.
3634
    field_purge_batch($batch_size);
3635

    
3636
    // The instance is gone.
3637
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
3638
    $this->assertEqual(count($instances), 0, 'The instance is gone');
3639

    
3640
    // The field still exists, not deleted, because it has a second instance.
3641
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
3642
    $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
3643
  }
3644

    
3645
  /**
3646
   * Verify that fields are preserved and purged correctly as multiple
3647
   * instances are deleted and purged.
3648
   */
3649
  function testPurgeField() {
3650
    // Start recording hook invocations.
3651
    field_test_memorize();
3652

    
3653
    $field = reset($this->fields);
3654

    
3655
    // Delete the first instance.
3656
    $bundle = reset($this->bundles);
3657
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3658
    field_delete_instance($instance);
3659

    
3660
    // Assert that hook_field_delete() was not called yet.
3661
    $mem = field_test_memorize();
3662
    $this->assertEqual(count($mem), 0, 'No field hooks were called.');
3663

    
3664
    // Purge the data.
3665
    field_purge_batch(10);
3666

    
3667
    // Check hooks invocations.
3668
    // - hook_field_load() (multiple hook) should have been called once, for all
3669
    // entities in the bundle.
3670
    // - hook_field_delete() should have been called once for each entity in the
3671
    // bundle.
3672
    $actual_hooks = field_test_memorize();
3673
    $hooks = array();
3674
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3675
    $hooks['field_test_field_load'][] = $stubs;
3676
    foreach ($stubs as $stub) {
3677
      $hooks['field_test_field_delete'][] = $stub;
3678
    }
3679
    $this->checkHooksInvocations($hooks, $actual_hooks);
3680

    
3681
    // Purge again to purge the instance.
3682
    field_purge_batch(0);
3683

    
3684
    // The field still exists, not deleted.
3685
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
3686
    $this->assertTrue(isset($fields[$field['id']]) && !$fields[$field['id']]['deleted'], 'The field exists and is not deleted');
3687

    
3688
    // Delete the second instance.
3689
    $bundle = next($this->bundles);
3690
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3691
    field_delete_instance($instance);
3692

    
3693
    // Assert that hook_field_delete() was not called yet.
3694
    $mem = field_test_memorize();
3695
    $this->assertEqual(count($mem), 0, 'No field hooks were called.');
3696

    
3697
    // Purge the data.
3698
    field_purge_batch(10);
3699

    
3700
    // Check hooks invocations (same as above, for the 2nd bundle).
3701
    $actual_hooks = field_test_memorize();
3702
    $hooks = array();
3703
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3704
    $hooks['field_test_field_load'][] = $stubs;
3705
    foreach ($stubs as $stub) {
3706
      $hooks['field_test_field_delete'][] = $stub;
3707
    }
3708
    $this->checkHooksInvocations($hooks, $actual_hooks);
3709

    
3710
    // The field still exists, deleted.
3711
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
3712
    $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');
3713

    
3714
    // Purge again to purge the instance and the field.
3715
    field_purge_batch(0);
3716

    
3717
    // The field is gone.
3718
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
3719
    $this->assertEqual(count($fields), 0, 'The field is purged.');
3720
  }
3721
}
3722

    
3723
/**
3724
 * Tests entity properties.
3725
 */
3726
class EntityPropertiesTestCase extends FieldTestCase {
3727
  public static function getInfo() {
3728
    return array(
3729
      'name' => 'Entity properties',
3730
      'description' => 'Tests entity properties.',
3731
      'group' => 'Entity API',
3732
    );
3733
  }
3734

    
3735
  function setUp() {
3736
    parent::setUp('field_test');
3737
  }
3738

    
3739
  /**
3740
   * Tests label key and label callback of an entity.
3741
   */
3742
  function testEntityLabel() {
3743
    $entity_types = array(
3744
      'test_entity_no_label',
3745
      'test_entity_label',
3746
      'test_entity_label_callback',
3747
    );
3748

    
3749
    $entity = field_test_create_stub_entity();
3750

    
3751
    foreach ($entity_types as $entity_type) {
3752
      $label = entity_label($entity_type, $entity);
3753

    
3754
      switch ($entity_type) {
3755
        case 'test_entity_no_label':
3756
          $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
3757
          break;
3758

    
3759
        case 'test_entity_label':
3760
          $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
3761
          break;
3762

    
3763
        case 'test_entity_label_callback':
3764
          $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
3765
          break;
3766
      }
3767
    }
3768
  }
3769
}