Projet

Général

Profil

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

root / htmltest / modules / field / tests / field.test @ 85ad3d82

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_attach_delete().
489
   */
490
  function testFieldAttachDelete() {
491
    $entity_type = 'test_entity';
492
    $langcode = LANGUAGE_NONE;
493
    $rev[0] = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
494

    
495
    // Create revision 0
496
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
497
    $rev[0]->{$this->field_name}[$langcode] = $values;
498
    field_attach_insert($entity_type, $rev[0]);
499

    
500
    // Create revision 1
501
    $rev[1] = field_test_create_stub_entity(0, 1, $this->instance['bundle']);
502
    $rev[1]->{$this->field_name}[$langcode] = $values;
503
    field_attach_update($entity_type, $rev[1]);
504

    
505
    // Create revision 2
506
    $rev[2] = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
507
    $rev[2]->{$this->field_name}[$langcode] = $values;
508
    field_attach_update($entity_type, $rev[2]);
509

    
510
    // Confirm each revision loads
511
    foreach (array_keys($rev) as $vid) {
512
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
513
      field_attach_load_revision($entity_type, array(0 => $read));
514
      $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
515
    }
516

    
517
    // Delete revision 1, confirm the other two still load.
518
    field_attach_delete_revision($entity_type, $rev[1]);
519
    foreach (array(0, 2) as $vid) {
520
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
521
      field_attach_load_revision($entity_type, array(0 => $read));
522
      $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity revision $vid has {$this->field['cardinality']} values.");
523
    }
524

    
525
    // Confirm the current revision still loads
526
    $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
527
    field_attach_load($entity_type, array(0 => $read));
528
    $this->assertEqual(count($read->{$this->field_name}[$langcode]), $this->field['cardinality'], "The test entity current revision has {$this->field['cardinality']} values.");
529

    
530
    // Delete all field data, confirm nothing loads
531
    field_attach_delete($entity_type, $rev[2]);
532
    foreach (array(0, 1, 2) as $vid) {
533
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
534
      field_attach_load_revision($entity_type, array(0 => $read));
535
      $this->assertIdentical($read->{$this->field_name}, array(), "The test entity revision $vid is deleted.");
536
    }
537
    $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
538
    field_attach_load($entity_type, array(0 => $read));
539
    $this->assertIdentical($read->{$this->field_name}, array(), 'The test entity current revision is deleted.');
540
  }
541

    
542
  /**
543
   * Test field_attach_create_bundle() and field_attach_rename_bundle().
544
   */
545
  function testFieldAttachCreateRenameBundle() {
546
    // Create a new bundle. This has to be initiated by the module so that its
547
    // hook_entity_info() is consistent.
548
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
549
    field_test_create_bundle($new_bundle);
550

    
551
    // Add an instance to that bundle.
552
    $this->instance['bundle'] = $new_bundle;
553
    field_create_instance($this->instance);
554

    
555
    // Save an entity with data in the field.
556
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
557
    $langcode = LANGUAGE_NONE;
558
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
559
    $entity->{$this->field_name}[$langcode] = $values;
560
    $entity_type = 'test_entity';
561
    field_attach_insert($entity_type, $entity);
562

    
563
    // Verify the field data is present on load.
564
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
565
    field_attach_load($entity_type, array(0 => $entity));
566
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Data is retrieved for the new bundle");
567

    
568
    // Rename the bundle. This has to be initiated by the module so that its
569
    // hook_entity_info() is consistent.
570
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
571
    field_test_rename_bundle($this->instance['bundle'], $new_bundle);
572

    
573
    // Check that the instance definition has been updated.
574
    $this->instance = field_info_instance($entity_type, $this->field_name, $new_bundle);
575
    $this->assertIdentical($this->instance['bundle'], $new_bundle, "Bundle name has been updated in the instance.");
576

    
577
    // Verify the field data is present on load.
578
    $entity = field_test_create_stub_entity(0, 0, $new_bundle);
579
    field_attach_load($entity_type, array(0 => $entity));
580
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), $this->field['cardinality'], "Bundle name has been updated in the field storage");
581
  }
582

    
583
  /**
584
   * Test field_attach_delete_bundle().
585
   */
586
  function testFieldAttachDeleteBundle() {
587
    // Create a new bundle. This has to be initiated by the module so that its
588
    // hook_entity_info() is consistent.
589
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
590
    field_test_create_bundle($new_bundle);
591

    
592
    // Add an instance to that bundle.
593
    $this->instance['bundle'] = $new_bundle;
594
    field_create_instance($this->instance);
595

    
596
    // Create a second field for the test bundle
597
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
598
    $field = array('field_name' => $field_name, 'type' => 'test_field', 'cardinality' => 1);
599
    field_create_field($field);
600
    $instance = array(
601
      'field_name' => $field_name,
602
      'entity_type' => 'test_entity',
603
      'bundle' => $this->instance['bundle'],
604
      'label' => $this->randomName() . '_label',
605
      'description' => $this->randomName() . '_description',
606
      'weight' => mt_rand(0, 127),
607
      // test_field has no instance settings
608
      'widget' => array(
609
        'type' => 'test_field_widget',
610
        'settings' => array(
611
          'size' => mt_rand(0, 255))));
612
    field_create_instance($instance);
613

    
614
    // Save an entity with data for both fields
615
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
616
    $langcode = LANGUAGE_NONE;
617
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
618
    $entity->{$this->field_name}[$langcode] = $values;
619
    $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues(1);
620
    field_attach_insert('test_entity', $entity);
621

    
622
    // Verify the fields are present on load
623
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
624
    field_attach_load('test_entity', array(0 => $entity));
625
    $this->assertEqual(count($entity->{$this->field_name}[$langcode]), 4, 'First field got loaded');
626
    $this->assertEqual(count($entity->{$field_name}[$langcode]), 1, 'Second field got loaded');
627

    
628
    // Delete the bundle. This has to be initiated by the module so that its
629
    // hook_entity_info() is consistent.
630
    field_test_delete_bundle($this->instance['bundle']);
631

    
632
    // Verify no data gets loaded
633
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
634
    field_attach_load('test_entity', array(0 => $entity));
635
    $this->assertFalse(isset($entity->{$this->field_name}[$langcode]), 'No data for first field');
636
    $this->assertFalse(isset($entity->{$field_name}[$langcode]), 'No data for second field');
637

    
638
    // Verify that the instances are gone
639
    $this->assertFalse(field_read_instance('test_entity', $this->field_name, $this->instance['bundle']), "First field is deleted");
640
    $this->assertFalse(field_read_instance('test_entity', $field_name, $instance['bundle']), "Second field is deleted");
641
  }
642
}
643

    
644
/**
645
 * Unit test class for non-storage related field_attach_* functions.
646
 */
647
class FieldAttachOtherTestCase extends FieldAttachTestCase {
648
  public static function getInfo() {
649
    return array(
650
      'name' => 'Field attach tests (other)',
651
      'description' => 'Test other Field Attach API functions.',
652
      'group' => 'Field API',
653
    );
654
  }
655

    
656
  /**
657
   * Test field_attach_view() and field_attach_prepare_view().
658
   */
659
  function testFieldAttachView() {
660
    $this->createFieldWithInstance('_2');
661

    
662
    $entity_type = 'test_entity';
663
    $entity_init = field_test_create_stub_entity();
664
    $langcode = LANGUAGE_NONE;
665
    $options = array('field_name' => $this->field_name_2);
666

    
667
    // Populate values to be displayed.
668
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
669
    $entity_init->{$this->field_name}[$langcode] = $values;
670
    $values_2 = $this->_generateTestFieldValues($this->field_2['cardinality']);
671
    $entity_init->{$this->field_name_2}[$langcode] = $values_2;
672

    
673
    // Simple formatter, label displayed.
674
    $entity = clone($entity_init);
675
    $formatter_setting = $this->randomName();
676
    $this->instance['display'] = array(
677
      'full' => array(
678
        'label' => 'above',
679
        'type' => 'field_test_default',
680
        'settings' => array(
681
          'test_formatter_setting' => $formatter_setting,
682
        )
683
      ),
684
    );
685
    field_update_instance($this->instance);
686
    $formatter_setting_2 = $this->randomName();
687
    $this->instance_2['display'] = array(
688
      'full' => array(
689
        'label' => 'above',
690
        'type' => 'field_test_default',
691
        'settings' => array(
692
          'test_formatter_setting' => $formatter_setting_2,
693
        )
694
      ),
695
    );
696
    field_update_instance($this->instance_2);
697
    // View all fields.
698
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
699
    $entity->content = field_attach_view($entity_type, $entity, 'full');
700
    $output = drupal_render($entity->content);
701
    $this->content = $output;
702
    $this->assertRaw($this->instance['label'], "First field's label is displayed.");
703
    foreach ($values as $delta => $value) {
704
      $this->content = $output;
705
      $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
706
    }
707
    $this->assertRaw($this->instance_2['label'], "Second field's label is displayed.");
708
    foreach ($values_2 as $delta => $value) {
709
      $this->content = $output;
710
      $this->assertRaw("$formatter_setting_2|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
711
    }
712
    // View single field (the second field).
713
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full', $langcode, $options);
714
    $entity->content = field_attach_view($entity_type, $entity, 'full', $langcode, $options);
715
    $output = drupal_render($entity->content);
716
    $this->content = $output;
717
    $this->assertNoRaw($this->instance['label'], "First field's label is not displayed.");
718
    foreach ($values as $delta => $value) {
719
      $this->content = $output;
720
      $this->assertNoRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
721
    }
722
    $this->assertRaw($this->instance_2['label'], "Second field's label is displayed.");
723
    foreach ($values_2 as $delta => $value) {
724
      $this->content = $output;
725
      $this->assertRaw("$formatter_setting_2|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
726
    }
727

    
728
    // Label hidden.
729
    $entity = clone($entity_init);
730
    $this->instance['display']['full']['label'] = 'hidden';
731
    field_update_instance($this->instance);
732
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
733
    $entity->content = field_attach_view($entity_type, $entity, 'full');
734
    $output = drupal_render($entity->content);
735
    $this->content = $output;
736
    $this->assertNoRaw($this->instance['label'], "Hidden label: label is not displayed.");
737

    
738
    // Field hidden.
739
    $entity = clone($entity_init);
740
    $this->instance['display'] = array(
741
      'full' => array(
742
        'label' => 'above',
743
        'type' => 'hidden',
744
      ),
745
    );
746
    field_update_instance($this->instance);
747
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
748
    $entity->content = field_attach_view($entity_type, $entity, 'full');
749
    $output = drupal_render($entity->content);
750
    $this->content = $output;
751
    $this->assertNoRaw($this->instance['label'], "Hidden field: label is not displayed.");
752
    foreach ($values as $delta => $value) {
753
      $this->assertNoRaw("$formatter_setting|{$value['value']}", "Hidden field: value $delta is not displayed.");
754
    }
755

    
756
    // Multiple formatter.
757
    $entity = clone($entity_init);
758
    $formatter_setting = $this->randomName();
759
    $this->instance['display'] = array(
760
      'full' => array(
761
        'label' => 'above',
762
        'type' => 'field_test_multiple',
763
        'settings' => array(
764
          'test_formatter_setting_multiple' => $formatter_setting,
765
        )
766
      ),
767
    );
768
    field_update_instance($this->instance);
769
    field_attach_prepare_view($entity_type, array($entity->ftid => $entity), 'full');
770
    $entity->content = field_attach_view($entity_type, $entity, 'full');
771
    $output = drupal_render($entity->content);
772
    $display = $formatter_setting;
773
    foreach ($values as $delta => $value) {
774
      $display .= "|$delta:{$value['value']}";
775
    }
776
    $this->content = $output;
777
    $this->assertRaw($display, "Multiple formatter: all values are displayed, formatter settings are applied.");
778

    
779
    // Test a formatter that uses hook_field_formatter_prepare_view().
780
    $entity = clone($entity_init);
781
    $formatter_setting = $this->randomName();
782
    $this->instance['display'] = array(
783
      'full' => array(
784
        'label' => 'above',
785
        'type' => 'field_test_with_prepare_view',
786
        'settings' => array(
787
          'test_formatter_setting_additional' => $formatter_setting,
788
        )
789
      ),
790
    );
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
    foreach ($values as $delta => $value) {
797
      $this->content = $output;
798
      $expected = $formatter_setting . '|' . $value['value'] . '|' . ($value['value'] + 1);
799
      $this->assertRaw($expected, "Value $delta is displayed, formatter settings are applied.");
800
    }
801

    
802
    // TODO:
803
    // - check display order with several fields
804

    
805
    // Preprocess template.
806
    $variables = array();
807
    field_attach_preprocess($entity_type, $entity, $entity->content, $variables);
808
    $result = TRUE;
809
    foreach ($values as $delta => $item) {
810
      if ($variables[$this->field_name][$delta]['value'] !== $item['value']) {
811
        $result = FALSE;
812
        break;
813
      }
814
    }
815
    $this->assertTrue($result, format_string('Variable $@field_name correctly populated.', array('@field_name' => $this->field_name)));
816
  }
817

    
818
  /**
819
   * Tests the 'multiple entity' behavior of field_attach_prepare_view().
820
   */
821
  function testFieldAttachPrepareViewMultiple() {
822
    $entity_type = 'test_entity';
823
    $langcode = LANGUAGE_NONE;
824

    
825
    // Set the instance to be hidden.
826
    $this->instance['display']['full']['type'] = 'hidden';
827
    field_update_instance($this->instance);
828

    
829
    // Set up a second instance on another bundle, with a formatter that uses
830
    // hook_field_formatter_prepare_view().
831
    field_test_create_bundle('test_bundle_2');
832
    $formatter_setting = $this->randomName();
833
    $this->instance2 = $this->instance;
834
    $this->instance2['bundle'] = 'test_bundle_2';
835
    $this->instance2['display']['full'] = array(
836
      'type' => 'field_test_with_prepare_view',
837
      'settings' => array(
838
        'test_formatter_setting_additional' => $formatter_setting,
839
      )
840
    );
841
    field_create_instance($this->instance2);
842

    
843
    // Create one entity in each bundle.
844
    $entity1_init = field_test_create_stub_entity(1, 1, 'test_bundle');
845
    $values1 = $this->_generateTestFieldValues($this->field['cardinality']);
846
    $entity1_init->{$this->field_name}[$langcode] = $values1;
847

    
848
    $entity2_init = field_test_create_stub_entity(2, 2, 'test_bundle_2');
849
    $values2 = $this->_generateTestFieldValues($this->field['cardinality']);
850
    $entity2_init->{$this->field_name}[$langcode] = $values2;
851

    
852
    // Run prepare_view, and check that the entities come out as expected.
853
    $entity1 = clone($entity1_init);
854
    $entity2 = clone($entity2_init);
855
    field_attach_prepare_view($entity_type, array($entity1->ftid => $entity1, $entity2->ftid => $entity2), 'full');
856
    $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
857
    $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
858

    
859
    // Same thing, reversed order.
860
    $entity1 = clone($entity1_init);
861
    $entity2 = clone($entity2_init);
862
    field_attach_prepare_view($entity_type, array($entity2->ftid => $entity2, $entity1->ftid => $entity1), 'full');
863
    $this->assertFalse(isset($entity1->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 1 did not run through the prepare_view hook.');
864
    $this->assertTrue(isset($entity2->{$this->field_name}[$langcode][0]['additional_formatter_value']), 'Entity 2 ran through the prepare_view hook.');
865
  }
866

    
867
  /**
868
   * Test field cache.
869
   */
870
  function testFieldAttachCache() {
871
    // Initialize random values and a test entity.
872
    $entity_init = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
873
    $langcode = LANGUAGE_NONE;
874
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
875

    
876
    // Non-cacheable entity type.
877
    $entity_type = 'test_entity';
878
    $cid = "field:$entity_type:{$entity_init->ftid}";
879

    
880
    // Check that no initial cache entry is present.
881
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no initial cache entry');
882

    
883
    // Save, and check that no cache entry is present.
884
    $entity = clone($entity_init);
885
    $entity->{$this->field_name}[$langcode] = $values;
886
    field_attach_insert($entity_type, $entity);
887
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no cache entry on insert');
888

    
889
    // Load, and check that no cache entry is present.
890
    $entity = clone($entity_init);
891
    field_attach_load($entity_type, array($entity->ftid => $entity));
892
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Non-cached: no cache entry on load');
893

    
894

    
895
    // Cacheable entity type.
896
    $entity_type = 'test_cacheable_entity';
897
    $cid = "field:$entity_type:{$entity_init->ftid}";
898
    $instance = $this->instance;
899
    $instance['entity_type'] = $entity_type;
900
    field_create_instance($instance);
901

    
902
    // Check that no initial cache entry is present.
903
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no initial cache entry');
904

    
905
    // Save, and check that no cache entry is present.
906
    $entity = clone($entity_init);
907
    $entity->{$this->field_name}[$langcode] = $values;
908
    field_attach_insert($entity_type, $entity);
909
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on insert');
910

    
911
    // Load a single field, and check that no cache entry is present.
912
    $entity = clone($entity_init);
913
    field_attach_load($entity_type, array($entity->ftid => $entity), FIELD_LOAD_CURRENT, array('field_id' => $this->field_id));
914
    $cache = cache_get($cid, 'cache_field');
915
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on loading a single field');
916

    
917
    // Load, and check that a cache entry is present with the expected values.
918
    $entity = clone($entity_init);
919
    field_attach_load($entity_type, array($entity->ftid => $entity));
920
    $cache = cache_get($cid, 'cache_field');
921
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
922

    
923
    // Update with different values, and check that the cache entry is wiped.
924
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
925
    $entity = clone($entity_init);
926
    $entity->{$this->field_name}[$langcode] = $values;
927
    field_attach_update($entity_type, $entity);
928
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on update');
929

    
930
    // Load, and check that a cache entry is present with the expected values.
931
    $entity = clone($entity_init);
932
    field_attach_load($entity_type, array($entity->ftid => $entity));
933
    $cache = cache_get($cid, 'cache_field');
934
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
935

    
936
    // Create a new revision, and check that the cache entry is wiped.
937
    $entity_init = field_test_create_stub_entity(1, 2, $this->instance['bundle']);
938
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
939
    $entity = clone($entity_init);
940
    $entity->{$this->field_name}[$langcode] = $values;
941
    field_attach_update($entity_type, $entity);
942
    $cache = cache_get($cid, 'cache_field');
943
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry on new revision creation');
944

    
945
    // Load, and check that a cache entry is present with the expected values.
946
    $entity = clone($entity_init);
947
    field_attach_load($entity_type, array($entity->ftid => $entity));
948
    $cache = cache_get($cid, 'cache_field');
949
    $this->assertEqual($cache->data[$this->field_name][$langcode], $values, 'Cached: correct cache entry on load');
950

    
951
    // Delete, and check that the cache entry is wiped.
952
    field_attach_delete($entity_type, $entity);
953
    $this->assertFalse(cache_get($cid, 'cache_field'), 'Cached: no cache entry after delete');
954
  }
955

    
956
  /**
957
   * Test field_attach_validate().
958
   *
959
   * Verify that field_attach_validate() invokes the correct
960
   * hook_field_validate.
961
   */
962
  function testFieldAttachValidate() {
963
    $this->createFieldWithInstance('_2');
964

    
965
    $entity_type = 'test_entity';
966
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
967
    $langcode = LANGUAGE_NONE;
968

    
969
    // Set up all but one values of the first field to generate errors.
970
    $values = array();
971
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
972
      $values[$delta]['value'] = -1;
973
    }
974
    // Arrange for item 1 not to generate an error
975
    $values[1]['value'] = 1;
976
    $entity->{$this->field_name}[$langcode] = $values;
977

    
978
    // Set up all values of the second field to generate errors.
979
    $values_2 = array();
980
    for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
981
      $values_2[$delta]['value'] = -1;
982
    }
983
    $entity->{$this->field_name_2}[$langcode] = $values_2;
984

    
985
    // Validate all fields.
986
    try {
987
      field_attach_validate($entity_type, $entity);
988
    }
989
    catch (FieldValidationException $e) {
990
      $errors = $e->errors;
991
    }
992

    
993
    foreach ($values as $delta => $value) {
994
      if ($value['value'] != 1) {
995
        $this->assertIdentical($errors[$this->field_name][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on first field's value $delta");
996
        $this->assertEqual(count($errors[$this->field_name][$langcode][$delta]), 1, "Only one error set on first field's value $delta");
997
        unset($errors[$this->field_name][$langcode][$delta]);
998
      }
999
      else {
1000
        $this->assertFalse(isset($errors[$this->field_name][$langcode][$delta]), "No error set on first field's value $delta");
1001
      }
1002
    }
1003
    foreach ($values_2 as $delta => $value) {
1004
      $this->assertIdentical($errors[$this->field_name_2][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on second field's value $delta");
1005
      $this->assertEqual(count($errors[$this->field_name_2][$langcode][$delta]), 1, "Only one error set on second field's value $delta");
1006
      unset($errors[$this->field_name_2][$langcode][$delta]);
1007
    }
1008
    $this->assertEqual(count($errors[$this->field_name][$langcode]), 0, 'No extraneous errors set for first field');
1009
    $this->assertEqual(count($errors[$this->field_name_2][$langcode]), 0, 'No extraneous errors set for second field');
1010

    
1011
    // Validate a single field.
1012
    $options = array('field_name' => $this->field_name_2);
1013
    try {
1014
      field_attach_validate($entity_type, $entity, $options);
1015
    }
1016
    catch (FieldValidationException $e) {
1017
      $errors = $e->errors;
1018
    }
1019

    
1020
    foreach ($values_2 as $delta => $value) {
1021
      $this->assertIdentical($errors[$this->field_name_2][$langcode][$delta][0]['error'], 'field_test_invalid', "Error set on second field's value $delta");
1022
      $this->assertEqual(count($errors[$this->field_name_2][$langcode][$delta]), 1, "Only one error set on second field's value $delta");
1023
      unset($errors[$this->field_name_2][$langcode][$delta]);
1024
    }
1025
    $this->assertFalse(isset($errors[$this->field_name]), 'No validation errors are set for the first field, despite it having errors');
1026
    $this->assertEqual(count($errors[$this->field_name_2][$langcode]), 0, 'No extraneous errors set for second field');
1027

    
1028
    // Check that cardinality is validated.
1029
    $entity->{$this->field_name_2}[$langcode] = $this->_generateTestFieldValues($this->field_2['cardinality'] + 1);
1030
    // When validating all fields.
1031
    try {
1032
      field_attach_validate($entity_type, $entity);
1033
    }
1034
    catch (FieldValidationException $e) {
1035
      $errors = $e->errors;
1036
    }
1037
    $this->assertEqual($errors[$this->field_name_2][$langcode][0][0]['error'], 'field_cardinality', 'Cardinality validation failed.');
1038
    // When validating a single field (the second field).
1039
    try {
1040
      field_attach_validate($entity_type, $entity, $options);
1041
    }
1042
    catch (FieldValidationException $e) {
1043
      $errors = $e->errors;
1044
    }
1045
    $this->assertEqual($errors[$this->field_name_2][$langcode][0][0]['error'], 'field_cardinality', 'Cardinality validation failed.');
1046
  }
1047

    
1048
  /**
1049
   * Test field_attach_form().
1050
   *
1051
   * This could be much more thorough, but it does verify that the correct
1052
   * widgets show up.
1053
   */
1054
  function testFieldAttachForm() {
1055
    $this->createFieldWithInstance('_2');
1056

    
1057
    $entity_type = 'test_entity';
1058
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
1059
    $langcode = LANGUAGE_NONE;
1060

    
1061
    // When generating form for all fields.
1062
    $form = array();
1063
    $form_state = form_state_defaults();
1064
    field_attach_form($entity_type, $entity, $form, $form_state);
1065

    
1066
    $this->assertEqual($form[$this->field_name][$langcode]['#title'], $this->instance['label'], "First field's form title is {$this->instance['label']}");
1067
    $this->assertEqual($form[$this->field_name_2][$langcode]['#title'], $this->instance_2['label'], "Second field's form title is {$this->instance_2['label']}");
1068
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
1069
      // field_test_widget uses 'textfield'
1070
        $this->assertEqual($form[$this->field_name][$langcode][$delta]['value']['#type'], 'textfield', "First field's form delta $delta widget is textfield");
1071
      }
1072
      for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
1073
        // field_test_widget uses 'textfield'
1074
        $this->assertEqual($form[$this->field_name_2][$langcode][$delta]['value']['#type'], 'textfield', "Second field's form delta $delta widget is textfield");
1075
      }
1076

    
1077
      // When generating form for a single field (the second field).
1078
      $options = array('field_name' => $this->field_name_2);
1079
      $form = array();
1080
      $form_state = form_state_defaults();
1081
      field_attach_form($entity_type, $entity, $form, $form_state, NULL, $options);
1082

    
1083
      $this->assertFalse(isset($form[$this->field_name]), 'The first field does not exist in the form');
1084
      $this->assertEqual($form[$this->field_name_2][$langcode]['#title'], $this->instance_2['label'], "Second field's form title is {$this->instance_2['label']}");
1085
      for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
1086
        // field_test_widget uses 'textfield'
1087
        $this->assertEqual($form[$this->field_name_2][$langcode][$delta]['value']['#type'], 'textfield', "Second field's form delta $delta widget is textfield");
1088
      }
1089
  }
1090

    
1091
  /**
1092
   * Test field_attach_submit().
1093
   */
1094
  function testFieldAttachSubmit() {
1095
    $this->createFieldWithInstance('_2');
1096

    
1097
    $entity_type = 'test_entity';
1098
    $entity_init = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
1099
    $langcode = LANGUAGE_NONE;
1100

    
1101
    // Build the form for all fields.
1102
    $form = array();
1103
    $form_state = form_state_defaults();
1104
    field_attach_form($entity_type, $entity_init, $form, $form_state);
1105

    
1106
    // Simulate incoming values.
1107
    // First field.
1108
    $values = array();
1109
    $weights = array();
1110
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
1111
      $values[$delta]['value'] = mt_rand(1, 127);
1112
      // Assign random weight.
1113
      do {
1114
        $weight = mt_rand(0, $this->field['cardinality']);
1115
      } while (in_array($weight, $weights));
1116
      $weights[$delta] = $weight;
1117
      $values[$delta]['_weight'] = $weight;
1118
    }
1119
    // Leave an empty value. 'field_test' fields are empty if empty().
1120
    $values[1]['value'] = 0;
1121
    // Second field.
1122
    $values_2 = array();
1123
    $weights_2 = array();
1124
    for ($delta = 0; $delta < $this->field_2['cardinality']; $delta++) {
1125
      $values_2[$delta]['value'] = mt_rand(1, 127);
1126
      // Assign random weight.
1127
      do {
1128
        $weight = mt_rand(0, $this->field_2['cardinality']);
1129
      } while (in_array($weight, $weights_2));
1130
      $weights_2[$delta] = $weight;
1131
      $values_2[$delta]['_weight'] = $weight;
1132
    }
1133
    // Leave an empty value. 'field_test' fields are empty if empty().
1134
    $values_2[1]['value'] = 0;
1135
    // Pretend the form has been built.
1136
    drupal_prepare_form('field_test_entity_form', $form, $form_state);
1137
    drupal_process_form('field_test_entity_form', $form, $form_state);
1138
    $form_state['values'][$this->field_name][$langcode] = $values;
1139
    $form_state['values'][$this->field_name_2][$langcode] = $values_2;
1140

    
1141
    // Call field_attach_submit() for all fields.
1142
    $entity = clone($entity_init);
1143
    field_attach_submit($entity_type, $entity, $form, $form_state);
1144

    
1145
    asort($weights);
1146
    asort($weights_2);
1147
    $expected_values = array();
1148
    $expected_values_2 = array();
1149
    foreach ($weights as $key => $value) {
1150
      if ($key != 1) {
1151
        $expected_values[] = array('value' => $values[$key]['value']);
1152
      }
1153
    }
1154
    $this->assertIdentical($entity->{$this->field_name}[$langcode], $expected_values, 'Submit filters empty values');
1155
    foreach ($weights_2 as $key => $value) {
1156
      if ($key != 1) {
1157
        $expected_values_2[] = array('value' => $values_2[$key]['value']);
1158
      }
1159
    }
1160
    $this->assertIdentical($entity->{$this->field_name_2}[$langcode], $expected_values_2, 'Submit filters empty values');
1161

    
1162
    // Call field_attach_submit() for a single field (the second field).
1163
    $options = array('field_name' => $this->field_name_2);
1164
    $entity = clone($entity_init);
1165
    field_attach_submit($entity_type, $entity, $form, $form_state, $options);
1166
    $expected_values_2 = array();
1167
    foreach ($weights_2 as $key => $value) {
1168
      if ($key != 1) {
1169
        $expected_values_2[] = array('value' => $values_2[$key]['value']);
1170
      }
1171
    }
1172
    $this->assertFalse(isset($entity->{$this->field_name}), 'The first field does not exist in the entity object');
1173
    $this->assertIdentical($entity->{$this->field_name_2}[$langcode], $expected_values_2, 'Submit filters empty values');
1174
  }
1175
}
1176

    
1177
class FieldInfoTestCase extends FieldTestCase {
1178

    
1179
  public static function getInfo() {
1180
    return array(
1181
      'name' => 'Field info tests',
1182
      'description' => 'Get information about existing fields, instances and bundles.',
1183
      'group' => 'Field API',
1184
    );
1185
  }
1186

    
1187
  function setUp() {
1188
    parent::setUp('field_test');
1189
  }
1190

    
1191
  /**
1192
   * Test that field types and field definitions are correcly cached.
1193
   */
1194
  function testFieldInfo() {
1195
    // Test that field_test module's fields, widgets, and formatters show up.
1196

    
1197
    $field_test_info = field_test_field_info();
1198
    // We need to account for the existence of user_field_info_alter().
1199
    foreach (array_keys($field_test_info) as $name) {
1200
      $field_test_info[$name]['instance_settings']['user_register_form'] = FALSE;
1201
    }
1202
    $info = field_info_field_types();
1203
    foreach ($field_test_info as $t_key => $field_type) {
1204
      foreach ($field_type as $key => $val) {
1205
        $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))));
1206
      }
1207
      $this->assertEqual($info[$t_key]['module'], 'field_test',  "Field type field_test module appears");
1208
    }
1209

    
1210
    $formatter_info = field_test_field_formatter_info();
1211
    $info = field_info_formatter_types();
1212
    foreach ($formatter_info as $f_key => $formatter) {
1213
      foreach ($formatter as $key => $val) {
1214
        $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))));
1215
      }
1216
      $this->assertEqual($info[$f_key]['module'], 'field_test',  "Formatter type field_test module appears");
1217
    }
1218

    
1219
    $widget_info = field_test_field_widget_info();
1220
    $info = field_info_widget_types();
1221
    foreach ($widget_info as $w_key => $widget) {
1222
      foreach ($widget as $key => $val) {
1223
        $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))));
1224
      }
1225
      $this->assertEqual($info[$w_key]['module'], 'field_test',  "Widget type field_test module appears");
1226
    }
1227

    
1228
    $storage_info = field_test_field_storage_info();
1229
    $info = field_info_storage_types();
1230
    foreach ($storage_info as $s_key => $storage) {
1231
      foreach ($storage as $key => $val) {
1232
        $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))));
1233
      }
1234
      $this->assertEqual($info[$s_key]['module'], 'field_test',  "Storage type field_test module appears");
1235
    }
1236

    
1237
    // Verify that no unexpected instances exist.
1238
    $instances = field_info_instances('test_entity');
1239
    $expected = array('test_bundle' => array());
1240
    $this->assertIdentical($instances, $expected, format_string("field_info_instances('test_entity') returns %expected.", array('%expected' => var_export($expected, TRUE))));
1241
    $instances = field_info_instances('test_entity', 'test_bundle');
1242
    $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'test_bundle') returns an empty array.");
1243

    
1244
    // Create a field, verify it shows up.
1245
    $core_fields = field_info_fields();
1246
    $field = array(
1247
      'field_name' => drupal_strtolower($this->randomName()),
1248
      'type' => 'test_field',
1249
    );
1250
    field_create_field($field);
1251
    $fields = field_info_fields();
1252
    $this->assertEqual(count($fields), count($core_fields) + 1, 'One new field exists');
1253
    $this->assertEqual($fields[$field['field_name']]['field_name'], $field['field_name'], 'info fields contains field name');
1254
    $this->assertEqual($fields[$field['field_name']]['type'], $field['type'], 'info fields contains field type');
1255
    $this->assertEqual($fields[$field['field_name']]['module'], 'field_test', 'info fields contains field module');
1256
    $settings = array('test_field_setting' => 'dummy test string');
1257
    foreach ($settings as $key => $val) {
1258
      $this->assertEqual($fields[$field['field_name']]['settings'][$key], $val, format_string('Field setting %key has correct default value %value', array('%key' => $key, '%value' => $val)));
1259
    }
1260
    $this->assertEqual($fields[$field['field_name']]['cardinality'], 1, 'info fields contains cardinality 1');
1261
    $this->assertEqual($fields[$field['field_name']]['active'], 1, 'info fields contains active 1');
1262

    
1263
    // Create an instance, verify that it shows up
1264
    $instance = array(
1265
      'field_name' => $field['field_name'],
1266
      'entity_type' => 'test_entity',
1267
      'bundle' => 'test_bundle',
1268
      'label' => $this->randomName(),
1269
      'description' => $this->randomName(),
1270
      'weight' => mt_rand(0, 127),
1271
      // test_field has no instance settings
1272
      'widget' => array(
1273
        'type' => 'test_field_widget',
1274
        'settings' => array(
1275
          'test_setting' => 999)));
1276
    field_create_instance($instance);
1277

    
1278
    $info = entity_get_info('test_entity');
1279
    $instances = field_info_instances('test_entity', $instance['bundle']);
1280
    $this->assertEqual(count($instances), 1, format_string('One instance shows up in info when attached to a bundle on a @label.', array(
1281
      '@label' => $info['label']
1282
    )));
1283
    $this->assertTrue($instance < $instances[$instance['field_name']], 'Instance appears in info correctly');
1284

    
1285
    // Test a valid entity type but an invalid bundle.
1286
    $instances = field_info_instances('test_entity', 'invalid_bundle');
1287
    $this->assertIdentical($instances, array(), "field_info_instances('test_entity', 'invalid_bundle') returns an empty array.");
1288

    
1289
    // Test invalid entity type and bundle.
1290
    $instances = field_info_instances('invalid_entity', $instance['bundle']);
1291
    $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity', 'test_bundle') returns an empty array.");
1292

    
1293
    // Test invalid entity type, no bundle provided.
1294
    $instances = field_info_instances('invalid_entity');
1295
    $this->assertIdentical($instances, array(), "field_info_instances('invalid_entity') returns an empty array.");
1296

    
1297
    // Test with an entity type that has no bundles.
1298
    $instances = field_info_instances('user');
1299
    $expected = array('user' => array());
1300
    $this->assertIdentical($instances, $expected, format_string("field_info_instances('user') returns %expected.", array('%expected' => var_export($expected, TRUE))));
1301
    $instances = field_info_instances('user', 'user');
1302
    $this->assertIdentical($instances, array(), "field_info_instances('user', 'user') returns an empty array.");
1303

    
1304
    // Test that querying for invalid entity types does not add entries in the
1305
    // list returned by field_info_instances().
1306
    field_info_cache_clear();
1307
    field_info_instances('invalid_entity', 'invalid_bundle');
1308
    // Simulate new request by clearing static caches.
1309
    drupal_static_reset();
1310
    field_info_instances('invalid_entity', 'invalid_bundle');
1311
    $instances = field_info_instances();
1312
    $this->assertFalse(isset($instances['invalid_entity']), 'field_info_instances() does not contain entries for the invalid entity type that was queried before');
1313
  }
1314

    
1315
  /**
1316
   * Test that cached field definitions are ready for current runtime context.
1317
   */
1318
  function testFieldPrepare() {
1319
    $field_definition = array(
1320
      'field_name' => 'field',
1321
      'type' => 'test_field',
1322
    );
1323
    field_create_field($field_definition);
1324

    
1325
    // Simulate a stored field definition missing a field setting (e.g. a
1326
    // third-party module adding a new field setting has been enabled, and
1327
    // existing fields do not know the setting yet).
1328
    $data = db_query('SELECT data FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']))->fetchField();
1329
    $data = unserialize($data);
1330
    $data['settings'] = array();
1331
    db_update('field_config')
1332
      ->fields(array('data' => serialize($data)))
1333
      ->condition('field_name', $field_definition['field_name'])
1334
      ->execute();
1335

    
1336
    field_cache_clear();
1337

    
1338
    // Read the field back.
1339
    $field = field_info_field($field_definition['field_name']);
1340

    
1341
    // Check that all expected settings are in place.
1342
    $field_type = field_info_field_types($field_definition['type']);
1343
    $this->assertIdentical($field['settings'], $field_type['settings'], 'All expected default field settings are present.');
1344
  }
1345

    
1346
  /**
1347
   * Test that cached instance definitions are ready for current runtime context.
1348
   */
1349
  function testInstancePrepare() {
1350
    $field_definition = array(
1351
      'field_name' => 'field',
1352
      'type' => 'test_field',
1353
    );
1354
    field_create_field($field_definition);
1355
    $instance_definition = array(
1356
      'field_name' => $field_definition['field_name'],
1357
      'entity_type' => 'test_entity',
1358
      'bundle' => 'test_bundle',
1359
    );
1360
    field_create_instance($instance_definition);
1361

    
1362
    // Simulate a stored instance definition missing various settings (e.g. a
1363
    // third-party module adding instance, widget or display settings has been
1364
    // enabled, but existing instances do not know the new settings).
1365
    $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();
1366
    $data = unserialize($data);
1367
    $data['settings'] = array();
1368
    $data['widget']['settings'] = 'unavailable_widget';
1369
    $data['widget']['settings'] = array();
1370
    $data['display']['default']['type'] = 'unavailable_formatter';
1371
    $data['display']['default']['settings'] = array();
1372
    db_update('field_config_instance')
1373
      ->fields(array('data' => serialize($data)))
1374
      ->condition('field_name', $instance_definition['field_name'])
1375
      ->condition('bundle', $instance_definition['bundle'])
1376
      ->execute();
1377

    
1378
    field_cache_clear();
1379

    
1380
    // Read the instance back.
1381
    $instance = field_info_instance($instance_definition['entity_type'], $instance_definition['field_name'], $instance_definition['bundle']);
1382

    
1383
    // Check that all expected instance settings are in place.
1384
    $field_type = field_info_field_types($field_definition['type']);
1385
    $this->assertIdentical($instance['settings'], $field_type['instance_settings'] , 'All expected instance settings are present.');
1386

    
1387
    // Check that the default widget is used and expected settings are in place.
1388
    $this->assertIdentical($instance['widget']['type'], $field_type['default_widget'], 'Unavailable widget replaced with default widget.');
1389
    $widget_type = field_info_widget_types($instance['widget']['type']);
1390
    $this->assertIdentical($instance['widget']['settings'], $widget_type['settings'] , 'All expected widget settings are present.');
1391

    
1392
    // Check that display settings are set for the 'default' mode.
1393
    $display = $instance['display']['default'];
1394
    $this->assertIdentical($display['type'], $field_type['default_formatter'], "Formatter is set for the 'default' view mode");
1395
    $formatter_type = field_info_formatter_types($display['type']);
1396
    $this->assertIdentical($display['settings'], $formatter_type['settings'] , "Formatter settings are set for the 'default' view mode");
1397
  }
1398

    
1399
  /**
1400
   * Test that instances on disabled entity types are filtered out.
1401
   */
1402
  function testInstanceDisabledEntityType() {
1403
    // For this test the field type and the entity type must be exposed by
1404
    // different modules.
1405
    $field_definition = array(
1406
      'field_name' => 'field',
1407
      'type' => 'test_field',
1408
    );
1409
    field_create_field($field_definition);
1410
    $instance_definition = array(
1411
      'field_name' => 'field',
1412
      'entity_type' => 'comment',
1413
      'bundle' => 'comment_node_article',
1414
    );
1415
    field_create_instance($instance_definition);
1416

    
1417
    // Disable coment module. This clears field_info cache.
1418
    module_disable(array('comment'));
1419
    $this->assertNull(field_info_instance('comment', 'field', 'comment_node_article'), 'No instances are returned on disabled entity types.');
1420
  }
1421

    
1422
  /**
1423
   * Test field_info_field_map().
1424
   */
1425
  function testFieldMap() {
1426
    // We will overlook fields created by the 'standard' install profile.
1427
    $exclude = field_info_field_map();
1428

    
1429
    // Create a new bundle for 'test_entity' entity type.
1430
    field_test_create_bundle('test_bundle_2');
1431

    
1432
    // Create a couple fields.
1433
    $fields  = array(
1434
      array(
1435
        'field_name' => 'field_1',
1436
        'type' => 'test_field',
1437
      ),
1438
      array(
1439
        'field_name' => 'field_2',
1440
        'type' => 'hidden_test_field',
1441
      ),
1442
    );
1443
    foreach ($fields as $field) {
1444
      field_create_field($field);
1445
    }
1446

    
1447
    // Create a couple instances.
1448
    $instances = array(
1449
      array(
1450
        'field_name' => 'field_1',
1451
        'entity_type' => 'test_entity',
1452
        'bundle' => 'test_bundle',
1453
      ),
1454
      array(
1455
        'field_name' => 'field_1',
1456
        'entity_type' => 'test_entity',
1457
        'bundle' => 'test_bundle_2',
1458
      ),
1459
      array(
1460
        'field_name' => 'field_2',
1461
        'entity_type' => 'test_entity',
1462
        'bundle' => 'test_bundle',
1463
      ),
1464
      array(
1465
        'field_name' => 'field_2',
1466
        'entity_type' => 'test_cacheable_entity',
1467
        'bundle' => 'test_bundle',
1468
      ),
1469
    );
1470
    foreach ($instances as $instance) {
1471
      field_create_instance($instance);
1472
    }
1473

    
1474
    $expected = array(
1475
      'field_1' => array(
1476
        'type' => 'test_field',
1477
        'bundles' => array(
1478
          'test_entity' => array('test_bundle', 'test_bundle_2'),
1479
        ),
1480
      ),
1481
      'field_2' => array(
1482
        'type' => 'hidden_test_field',
1483
        'bundles' => array(
1484
          'test_entity' => array('test_bundle'),
1485
          'test_cacheable_entity' => array('test_bundle'),
1486
        ),
1487
      ),
1488
    );
1489

    
1490
    // Check that the field map is correct.
1491
    $map = field_info_field_map();
1492
    $map = array_diff_key($map, $exclude);
1493
    $this->assertEqual($map, $expected);
1494
  }
1495

    
1496
  /**
1497
   * Test that the field_info settings convenience functions work.
1498
   */
1499
  function testSettingsInfo() {
1500
    $info = field_test_field_info();
1501
    // We need to account for the existence of user_field_info_alter().
1502
    foreach (array_keys($info) as $name) {
1503
      $info[$name]['instance_settings']['user_register_form'] = FALSE;
1504
    }
1505
    foreach ($info as $type => $data) {
1506
      $this->assertIdentical(field_info_field_settings($type), $data['settings'], format_string("field_info_field_settings returns %type's field settings", array('%type' => $type)));
1507
      $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)));
1508
    }
1509

    
1510
    $info = field_test_field_widget_info();
1511
    foreach ($info as $type => $data) {
1512
      $this->assertIdentical(field_info_widget_settings($type), $data['settings'], format_string("field_info_widget_settings returns %type's widget settings", array('%type' => $type)));
1513
    }
1514

    
1515
    $info = field_test_field_formatter_info();
1516
    foreach ($info as $type => $data) {
1517
      $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], format_string("field_info_formatter_settings returns %type's formatter settings", array('%type' => $type)));
1518
    }
1519
  }
1520

    
1521
  /**
1522
   * Tests that the field info cache can be built correctly.
1523
   */
1524
  function testFieldInfoCache() {
1525
    // Create a test field and ensure it's in the array returned by
1526
    // field_info_fields().
1527
    $field_name = drupal_strtolower($this->randomName());
1528
    $field = array(
1529
      'field_name' => $field_name,
1530
      'type' => 'test_field',
1531
    );
1532
    field_create_field($field);
1533
    $fields = field_info_fields();
1534
    $this->assertTrue(isset($fields[$field_name]), 'The test field is initially found in the array returned by field_info_fields().');
1535

    
1536
    // Now rebuild the field info cache, and set a variable which will cause
1537
    // the cache to be cleared while it's being rebuilt; see
1538
    // field_test_entity_info(). Ensure the test field is still in the returned
1539
    // array.
1540
    field_info_cache_clear();
1541
    variable_set('field_test_clear_info_cache_in_hook_entity_info', TRUE);
1542
    $fields = field_info_fields();
1543
    $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.');
1544
  }
1545
}
1546

    
1547
class FieldFormTestCase extends FieldTestCase {
1548
  public static function getInfo() {
1549
    return array(
1550
      'name' => 'Field form tests',
1551
      'description' => 'Test Field form handling.',
1552
      'group' => 'Field API',
1553
    );
1554
  }
1555

    
1556
  function setUp() {
1557
    parent::setUp('field_test');
1558

    
1559
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
1560
    $this->drupalLogin($web_user);
1561

    
1562
    $this->field_single = array('field_name' => 'field_single', 'type' => 'test_field');
1563
    $this->field_multiple = array('field_name' => 'field_multiple', 'type' => 'test_field', 'cardinality' => 4);
1564
    $this->field_unlimited = array('field_name' => 'field_unlimited', 'type' => 'test_field', 'cardinality' => FIELD_CARDINALITY_UNLIMITED);
1565

    
1566
    $this->instance = array(
1567
      'entity_type' => 'test_entity',
1568
      'bundle' => 'test_bundle',
1569
      'label' => $this->randomName() . '_label',
1570
      'description' => $this->randomName() . '_description',
1571
      'weight' => mt_rand(0, 127),
1572
      'settings' => array(
1573
        'test_instance_setting' => $this->randomName(),
1574
      ),
1575
      'widget' => array(
1576
        'type' => 'test_field_widget',
1577
        'label' => 'Test Field',
1578
        'settings' => array(
1579
          'test_widget_setting' => $this->randomName(),
1580
        )
1581
      )
1582
    );
1583
  }
1584

    
1585
  function testFieldFormSingle() {
1586
    $this->field = $this->field_single;
1587
    $this->field_name = $this->field['field_name'];
1588
    $this->instance['field_name'] = $this->field_name;
1589
    field_create_field($this->field);
1590
    field_create_instance($this->instance);
1591
    $langcode = LANGUAGE_NONE;
1592

    
1593
    // Display creation form.
1594
    $this->drupalGet('test-entity/add/test-bundle');
1595
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget is displayed');
1596
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
1597
    // TODO : check that the widget is populated with default value ?
1598

    
1599
    // Submit with invalid value (field-level validation).
1600
    $edit = array("{$this->field_name}[$langcode][0][value]" => -1);
1601
    $this->drupalPost(NULL, $edit, t('Save'));
1602
    $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->instance['label'])), 'Field validation fails with invalid input.');
1603
    // TODO : check that the correct field is flagged for error.
1604

    
1605
    // Create an entity
1606
    $value = mt_rand(1, 127);
1607
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
1608
    $this->drupalPost(NULL, $edit, t('Save'));
1609
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1610
    $id = $match[1];
1611
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
1612
    $entity = field_test_entity_test_load($id);
1613
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
1614

    
1615
    // Display edit form.
1616
    $this->drupalGet('test-entity/manage/' . $id . '/edit');
1617
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", $value, 'Widget is displayed with the correct default value');
1618
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
1619

    
1620
    // Update the entity.
1621
    $value = mt_rand(1, 127);
1622
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
1623
    $this->drupalPost(NULL, $edit, t('Save'));
1624
    $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
1625
    $entity = field_test_entity_test_load($id);
1626
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was updated');
1627

    
1628
    // Empty the field.
1629
    $value = '';
1630
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
1631
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
1632
    $this->assertRaw(t('test_entity @id has been updated.', array('@id' => $id)), 'Entity was updated');
1633
    $entity = field_test_entity_test_load($id);
1634
    $this->assertIdentical($entity->{$this->field_name}, array(), 'Field was emptied');
1635

    
1636
  }
1637

    
1638
  function testFieldFormSingleRequired() {
1639
    $this->field = $this->field_single;
1640
    $this->field_name = $this->field['field_name'];
1641
    $this->instance['field_name'] = $this->field_name;
1642
    $this->instance['required'] = TRUE;
1643
    field_create_field($this->field);
1644
    field_create_instance($this->instance);
1645
    $langcode = LANGUAGE_NONE;
1646

    
1647
    // Submit with missing required value.
1648
    $edit = array();
1649
    $this->drupalPost('test-entity/add/test-bundle', $edit, t('Save'));
1650
    $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
1651

    
1652
    // Create an entity
1653
    $value = mt_rand(1, 127);
1654
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
1655
    $this->drupalPost(NULL, $edit, t('Save'));
1656
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1657
    $id = $match[1];
1658
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
1659
    $entity = field_test_entity_test_load($id);
1660
    $this->assertEqual($entity->{$this->field_name}[$langcode][0]['value'], $value, 'Field value was saved');
1661

    
1662
    // Edit with missing required value.
1663
    $value = '';
1664
    $edit = array("{$this->field_name}[$langcode][0][value]" => $value);
1665
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
1666
    $this->assertRaw(t('!name field is required.', array('!name' => $this->instance['label'])), 'Required field with no value fails validation');
1667
  }
1668

    
1669
//  function testFieldFormMultiple() {
1670
//    $this->field = $this->field_multiple;
1671
//    $this->field_name = $this->field['field_name'];
1672
//    $this->instance['field_name'] = $this->field_name;
1673
//    field_create_field($this->field);
1674
//    field_create_instance($this->instance);
1675
//  }
1676

    
1677
  function testFieldFormUnlimited() {
1678
    $this->field = $this->field_unlimited;
1679
    $this->field_name = $this->field['field_name'];
1680
    $this->instance['field_name'] = $this->field_name;
1681
    field_create_field($this->field);
1682
    field_create_instance($this->instance);
1683
    $langcode = LANGUAGE_NONE;
1684

    
1685
    // Display creation form -> 1 widget.
1686
    $this->drupalGet('test-entity/add/test-bundle');
1687
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
1688
    $this->assertNoField("{$this->field_name}[$langcode][1][value]", 'No extraneous widget is displayed');
1689

    
1690
    // Press 'add more' button -> 2 widgets.
1691
    $this->drupalPost(NULL, array(), t('Add another item'));
1692
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
1693
    $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
1694
    $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
1695
    // TODO : check that non-field inpurs are preserved ('title')...
1696

    
1697
    // Yet another time so that we can play with more values -> 3 widgets.
1698
    $this->drupalPost(NULL, array(), t('Add another item'));
1699

    
1700
    // Prepare values and weights.
1701
    $count = 3;
1702
    $delta_range = $count - 1;
1703
    $values = $weights = $pattern = $expected_values = $edit = array();
1704
    for ($delta = 0; $delta <= $delta_range; $delta++) {
1705
      // Assign unique random values and weights.
1706
      do {
1707
        $value = mt_rand(1, 127);
1708
      } while (in_array($value, $values));
1709
      do {
1710
        $weight = mt_rand(-$delta_range, $delta_range);
1711
      } while (in_array($weight, $weights));
1712
      $edit["$this->field_name[$langcode][$delta][value]"] = $value;
1713
      $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
1714
      // We'll need three slightly different formats to check the values.
1715
      $values[$delta] = $value;
1716
      $weights[$delta] = $weight;
1717
      $field_values[$weight]['value'] = (string) $value;
1718
      $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
1719
    }
1720

    
1721
    // Press 'add more' button -> 4 widgets
1722
    $this->drupalPost(NULL, $edit, t('Add another item'));
1723
    for ($delta = 0; $delta <= $delta_range; $delta++) {
1724
      $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
1725
      $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
1726
    }
1727
    ksort($pattern);
1728
    $pattern = implode('.*', array_values($pattern));
1729
    $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
1730
    $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
1731
    $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
1732
    $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
1733

    
1734
    // Submit the form and create the entity.
1735
    $this->drupalPost(NULL, $edit, t('Save'));
1736
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1737
    $id = $match[1];
1738
    $this->assertRaw(t('test_entity @id has been created.', array('@id' => $id)), 'Entity was created');
1739
    $entity = field_test_entity_test_load($id);
1740
    ksort($field_values);
1741
    $field_values = array_values($field_values);
1742
    $this->assertIdentical($entity->{$this->field_name}[$langcode], $field_values, 'Field values were saved in the correct order');
1743

    
1744
    // Display edit form: check that the expected number of widgets is
1745
    // displayed, with correct values change values, reorder, leave an empty
1746
    // value in the middle.
1747
    // Submit: check that the entity is updated with correct values
1748
    // Re-submit: check that the field can be emptied.
1749

    
1750
    // Test with several multiple fields in a form
1751
  }
1752

    
1753
  /**
1754
   * Tests widget handling of multiple required radios.
1755
   */
1756
  function testFieldFormMultivalueWithRequiredRadio() {
1757
    // Create a multivalue test field.
1758
    $this->field = $this->field_unlimited;
1759
    $this->field_name = $this->field['field_name'];
1760
    $this->instance['field_name'] = $this->field_name;
1761
    field_create_field($this->field);
1762
    field_create_instance($this->instance);
1763
    $langcode = LANGUAGE_NONE;
1764

    
1765
    // Add a required radio field.
1766
    field_create_field(array(
1767
      'field_name' => 'required_radio_test',
1768
      'type' => 'list_text',
1769
      'settings' => array(
1770
        'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
1771
      ),
1772
    ));
1773
    field_create_instance(array(
1774
      'field_name' => 'required_radio_test',
1775
      'entity_type' => 'test_entity',
1776
      'bundle' => 'test_bundle',
1777
      'required' => TRUE,
1778
      'widget' => array(
1779
        'type' => 'options_buttons',
1780
      ),
1781
    ));
1782

    
1783
    // Display creation form.
1784
    $this->drupalGet('test-entity/add/test-bundle');
1785

    
1786
    // Press the 'Add more' button.
1787
    $this->drupalPost(NULL, array(), t('Add another item'));
1788

    
1789
    // Verify that no error is thrown by the radio element.
1790
    $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
1791

    
1792
    // Verify that the widget is added.
1793
    $this->assertFieldByName("{$this->field_name}[$langcode][0][value]", '', 'Widget 1 is displayed');
1794
    $this->assertFieldByName("{$this->field_name}[$langcode][1][value]", '', 'New widget is displayed');
1795
    $this->assertNoField("{$this->field_name}[$langcode][2][value]", 'No extraneous widget is displayed');
1796
  }
1797

    
1798
  function testFieldFormJSAddMore() {
1799
    $this->field = $this->field_unlimited;
1800
    $this->field_name = $this->field['field_name'];
1801
    $this->instance['field_name'] = $this->field_name;
1802
    field_create_field($this->field);
1803
    field_create_instance($this->instance);
1804
    $langcode = LANGUAGE_NONE;
1805

    
1806
    // Display creation form -> 1 widget.
1807
    $this->drupalGet('test-entity/add/test-bundle');
1808

    
1809
    // Press 'add more' button a couple times -> 3 widgets.
1810
    // drupalPostAJAX() will not work iteratively, so we add those through
1811
    // non-JS submission.
1812
    $this->drupalPost(NULL, array(), t('Add another item'));
1813
    $this->drupalPost(NULL, array(), t('Add another item'));
1814

    
1815
    // Prepare values and weights.
1816
    $count = 3;
1817
    $delta_range = $count - 1;
1818
    $values = $weights = $pattern = $expected_values = $edit = array();
1819
    for ($delta = 0; $delta <= $delta_range; $delta++) {
1820
      // Assign unique random values and weights.
1821
      do {
1822
        $value = mt_rand(1, 127);
1823
      } while (in_array($value, $values));
1824
      do {
1825
        $weight = mt_rand(-$delta_range, $delta_range);
1826
      } while (in_array($weight, $weights));
1827
      $edit["$this->field_name[$langcode][$delta][value]"] = $value;
1828
      $edit["$this->field_name[$langcode][$delta][_weight]"] = $weight;
1829
      // We'll need three slightly different formats to check the values.
1830
      $values[$delta] = $value;
1831
      $weights[$delta] = $weight;
1832
      $field_values[$weight]['value'] = (string) $value;
1833
      $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
1834
    }
1835
    // Press 'add more' button through Ajax, and place the expected HTML result
1836
    // as the tested content.
1837
    $commands = $this->drupalPostAJAX(NULL, $edit, $this->field_name . '_add_more');
1838
    $this->content = $commands[1]['data'];
1839

    
1840
    for ($delta = 0; $delta <= $delta_range; $delta++) {
1841
      $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
1842
      $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
1843
    }
1844
    ksort($pattern);
1845
    $pattern = implode('.*', array_values($pattern));
1846
    $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
1847
    $this->assertFieldByName("$this->field_name[$langcode][$delta][value]", '', "New widget is displayed");
1848
    $this->assertFieldByName("$this->field_name[$langcode][$delta][_weight]", $delta, "New widget has the right weight");
1849
    $this->assertNoField("$this->field_name[$langcode][" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
1850
  }
1851

    
1852
  /**
1853
   * Tests widgets handling multiple values.
1854
   */
1855
  function testFieldFormMultipleWidget() {
1856
    // Create a field with fixed cardinality and an instance using a multiple
1857
    // widget.
1858
    $this->field = $this->field_multiple;
1859
    $this->field_name = $this->field['field_name'];
1860
    $this->instance['field_name'] = $this->field_name;
1861
    $this->instance['widget']['type'] = 'test_field_widget_multiple';
1862
    field_create_field($this->field);
1863
    field_create_instance($this->instance);
1864
    $langcode = LANGUAGE_NONE;
1865

    
1866
    // Display creation form.
1867
    $this->drupalGet('test-entity/add/test-bundle');
1868
    $this->assertFieldByName("{$this->field_name}[$langcode]", '', 'Widget is displayed.');
1869

    
1870
    // Create entity with three values.
1871
    $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3');
1872
    $this->drupalPost(NULL, $edit, t('Save'));
1873
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1874
    $id = $match[1];
1875

    
1876
    // Check that the values were saved.
1877
    $entity_init = field_test_create_stub_entity($id);
1878
    $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
1879

    
1880
    // Display the form, check that the values are correctly filled in.
1881
    $this->drupalGet('test-entity/manage/' . $id . '/edit');
1882
    $this->assertFieldByName("{$this->field_name}[$langcode]", '1, 2, 3', 'Widget is displayed.');
1883

    
1884
    // Submit the form with more values than the field accepts.
1885
    $edit = array("{$this->field_name}[$langcode]" => '1, 2, 3, 4, 5');
1886
    $this->drupalPost(NULL, $edit, t('Save'));
1887
    $this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.');
1888
    // Check that the field values were not submitted.
1889
    $this->assertFieldValues($entity_init, $this->field_name, $langcode, array(1, 2, 3));
1890
  }
1891

    
1892
  /**
1893
   * Tests fields with no 'edit' access.
1894
   */
1895
  function testFieldFormAccess() {
1896
    // Create a "regular" field.
1897
    $field = $this->field_single;
1898
    $field_name = $field['field_name'];
1899
    $instance = $this->instance;
1900
    $instance['field_name'] = $field_name;
1901
    field_create_field($field);
1902
    field_create_instance($instance);
1903

    
1904
    // Create a field with no edit access - see field_test_field_access().
1905
    $field_no_access = array(
1906
      'field_name' => 'field_no_edit_access',
1907
      'type' => 'test_field',
1908
    );
1909
    $field_name_no_access = $field_no_access['field_name'];
1910
    $instance_no_access = array(
1911
      'field_name' => $field_name_no_access,
1912
      'entity_type' => 'test_entity',
1913
      'bundle' => 'test_bundle',
1914
      'default_value' => array(0 => array('value' => 99)),
1915
    );
1916
    field_create_field($field_no_access);
1917
    field_create_instance($instance_no_access);
1918

    
1919
    $langcode = LANGUAGE_NONE;
1920

    
1921
    // Test that the form structure includes full information for each delta
1922
    // apart from #access.
1923
    $entity_type = 'test_entity';
1924
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
1925

    
1926
    $form = array();
1927
    $form_state = form_state_defaults();
1928
    field_attach_form($entity_type, $entity, $form, $form_state);
1929

    
1930
    $this->assertEqual($form[$field_name_no_access][$langcode][0]['value']['#entity_type'], $entity_type, 'The correct entity type is set in the field structure.');
1931
    $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
1932

    
1933
    // Display creation form.
1934
    $this->drupalGet('test-entity/add/test-bundle');
1935
    $this->assertNoFieldByName("{$field_name_no_access}[$langcode][0][value]", '', 'Widget is not displayed if field access is denied.');
1936

    
1937
    // Create entity.
1938
    $edit = array("{$field_name}[$langcode][0][value]" => 1);
1939
    $this->drupalPost(NULL, $edit, t('Save'));
1940
    preg_match('|test-entity/manage/(\d+)/edit|', $this->url, $match);
1941
    $id = $match[1];
1942

    
1943
    // Check that the default value was saved.
1944
    $entity = field_test_entity_test_load($id);
1945
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'Default value was saved for the field with no edit access.');
1946
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 1, 'Entered value vas saved for the field with edit access.');
1947

    
1948
    // Create a new revision.
1949
    $edit = array("{$field_name}[$langcode][0][value]" => 2, 'revision' => TRUE);
1950
    $this->drupalPost('test-entity/manage/' . $id . '/edit', $edit, t('Save'));
1951

    
1952
    // Check that the new revision has the expected values.
1953
    $entity = field_test_entity_test_load($id);
1954
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'New revision has the expected value for the field with no edit access.');
1955
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, 'New revision has the expected value for the field with edit access.');
1956

    
1957
    // Check that the revision is also saved in the revisions table.
1958
    $entity = field_test_entity_test_load($id, $entity->ftvid);
1959
    $this->assertEqual($entity->{$field_name_no_access}[$langcode][0]['value'], 99, 'New revision has the expected value for the field with no edit access.');
1960
    $this->assertEqual($entity->{$field_name}[$langcode][0]['value'], 2, 'New revision has the expected value for the field with edit access.');
1961
  }
1962

    
1963
  /**
1964
   * Tests Field API form integration within a subform.
1965
   */
1966
  function testNestedFieldForm() {
1967
    // Add two instances on the 'test_bundle'
1968
    field_create_field($this->field_single);
1969
    field_create_field($this->field_unlimited);
1970
    $this->instance['field_name'] = 'field_single';
1971
    $this->instance['label'] = 'Single field';
1972
    field_create_instance($this->instance);
1973
    $this->instance['field_name'] = 'field_unlimited';
1974
    $this->instance['label'] = 'Unlimited field';
1975
    field_create_instance($this->instance);
1976

    
1977
    // Create two entities.
1978
    $entity_1 = field_test_create_stub_entity(1, 1);
1979
    $entity_1->is_new = TRUE;
1980
    $entity_1->field_single[LANGUAGE_NONE][] = array('value' => 0);
1981
    $entity_1->field_unlimited[LANGUAGE_NONE][] = array('value' => 1);
1982
    field_test_entity_save($entity_1);
1983

    
1984
    $entity_2 = field_test_create_stub_entity(2, 2);
1985
    $entity_2->is_new = TRUE;
1986
    $entity_2->field_single[LANGUAGE_NONE][] = array('value' => 10);
1987
    $entity_2->field_unlimited[LANGUAGE_NONE][] = array('value' => 11);
1988
    field_test_entity_save($entity_2);
1989

    
1990
    // Display the 'combined form'.
1991
    $this->drupalGet('test-entity/nested/1/2');
1992
    $this->assertFieldByName('field_single[und][0][value]', 0, 'Entity 1: field_single value appears correctly is the form.');
1993
    $this->assertFieldByName('field_unlimited[und][0][value]', 1, 'Entity 1: field_unlimited value 0 appears correctly is the form.');
1994
    $this->assertFieldByName('entity_2[field_single][und][0][value]', 10, 'Entity 2: field_single value appears correctly is the form.');
1995
    $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 11, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
1996

    
1997
    // Submit the form and check that the entities are updated accordingly.
1998
    $edit = array(
1999
      'field_single[und][0][value]' => 1,
2000
      'field_unlimited[und][0][value]' => 2,
2001
      'field_unlimited[und][1][value]' => 3,
2002
      'entity_2[field_single][und][0][value]' => 11,
2003
      'entity_2[field_unlimited][und][0][value]' => 12,
2004
      'entity_2[field_unlimited][und][1][value]' => 13,
2005
    );
2006
    $this->drupalPost(NULL, $edit, t('Save'));
2007
    field_cache_clear();
2008
    $entity_1 = field_test_create_stub_entity(1);
2009
    $entity_2 = field_test_create_stub_entity(2);
2010
    $this->assertFieldValues($entity_1, 'field_single', LANGUAGE_NONE, array(1));
2011
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(2, 3));
2012
    $this->assertFieldValues($entity_2, 'field_single', LANGUAGE_NONE, array(11));
2013
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(12, 13));
2014

    
2015
    // Submit invalid values and check that errors are reported on the
2016
    // correct widgets.
2017
    $edit = array(
2018
      'field_unlimited[und][1][value]' => -1,
2019
    );
2020
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
2021
    $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 1: the field validation error was reported.');
2022
    $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-field-unlimited-und-1-value'));
2023
    $this->assertTrue($error_field, 'Entity 1: the error was flagged on the correct element.');
2024
    $edit = array(
2025
      'entity_2[field_unlimited][und][1][value]' => -1,
2026
    );
2027
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
2028
    $this->assertRaw(t('%label does not accept the value -1', array('%label' => 'Unlimited field')), 'Entity 2: the field validation error was reported.');
2029
    $error_field = $this->xpath('//input[@id=:id and contains(@class, "error")]', array(':id' => 'edit-entity-2-field-unlimited-und-1-value'));
2030
    $this->assertTrue($error_field, 'Entity 2: the error was flagged on the correct element.');
2031

    
2032
    // Test that reordering works on both entities.
2033
    $edit = array(
2034
      'field_unlimited[und][0][_weight]' => 0,
2035
      'field_unlimited[und][1][_weight]' => -1,
2036
      'entity_2[field_unlimited][und][0][_weight]' => 0,
2037
      'entity_2[field_unlimited][und][1][_weight]' => -1,
2038
    );
2039
    $this->drupalPost('test-entity/nested/1/2', $edit, t('Save'));
2040
    field_cache_clear();
2041
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
2042
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 12));
2043

    
2044
    // Test the 'add more' buttons. Only Ajax submission is tested, because
2045
    // the two 'add more' buttons present in the form have the same #value,
2046
    // which confuses drupalPost().
2047
    // 'Add more' button in the first entity:
2048
    $this->drupalGet('test-entity/nested/1/2');
2049
    $this->drupalPostAJAX(NULL, array(), 'field_unlimited_add_more');
2050
    $this->assertFieldByName('field_unlimited[und][0][value]', 3, 'Entity 1: field_unlimited value 0 appears correctly is the form.');
2051
    $this->assertFieldByName('field_unlimited[und][1][value]', 2, 'Entity 1: field_unlimited value 1 appears correctly is the form.');
2052
    $this->assertFieldByName('field_unlimited[und][2][value]', '', 'Entity 1: field_unlimited value 2 appears correctly is the form.');
2053
    $this->assertFieldByName('field_unlimited[und][3][value]', '', 'Entity 1: an empty widget was added for field_unlimited value 3.');
2054
    // 'Add more' button in the first entity (changing field values):
2055
    $edit = array(
2056
      'entity_2[field_unlimited][und][0][value]' => 13,
2057
      'entity_2[field_unlimited][und][1][value]' => 14,
2058
      'entity_2[field_unlimited][und][2][value]' => 15,
2059
    );
2060
    $this->drupalPostAJAX(NULL, $edit, 'entity_2_field_unlimited_add_more');
2061
    $this->assertFieldByName('entity_2[field_unlimited][und][0][value]', 13, 'Entity 2: field_unlimited value 0 appears correctly is the form.');
2062
    $this->assertFieldByName('entity_2[field_unlimited][und][1][value]', 14, 'Entity 2: field_unlimited value 1 appears correctly is the form.');
2063
    $this->assertFieldByName('entity_2[field_unlimited][und][2][value]', 15, 'Entity 2: field_unlimited value 2 appears correctly is the form.');
2064
    $this->assertFieldByName('entity_2[field_unlimited][und][3][value]', '', 'Entity 2: an empty widget was added for field_unlimited value 3.');
2065
    // Save the form and check values are saved correclty.
2066
    $this->drupalPost(NULL, array(), t('Save'));
2067
    field_cache_clear();
2068
    $this->assertFieldValues($entity_1, 'field_unlimited', LANGUAGE_NONE, array(3, 2));
2069
    $this->assertFieldValues($entity_2, 'field_unlimited', LANGUAGE_NONE, array(13, 14, 15));
2070
  }
2071
}
2072

    
2073
class FieldDisplayAPITestCase extends FieldTestCase {
2074
  public static function getInfo() {
2075
    return array(
2076
      'name' => 'Field Display API tests',
2077
      'description' => 'Test the display API.',
2078
      'group' => 'Field API',
2079
    );
2080
  }
2081

    
2082
  function setUp() {
2083
    parent::setUp('field_test');
2084

    
2085
    // Create a field and instance.
2086
    $this->field_name = 'test_field';
2087
    $this->label = $this->randomName();
2088
    $this->cardinality = 4;
2089

    
2090
    $this->field = array(
2091
      'field_name' => $this->field_name,
2092
      'type' => 'test_field',
2093
      'cardinality' => $this->cardinality,
2094
    );
2095
    $this->instance = array(
2096
      'field_name' => $this->field_name,
2097
      'entity_type' => 'test_entity',
2098
      'bundle' => 'test_bundle',
2099
      'label' => $this->label,
2100
      'display' => array(
2101
        'default' => array(
2102
          'type' => 'field_test_default',
2103
          'settings' => array(
2104
            'test_formatter_setting' => $this->randomName(),
2105
          ),
2106
        ),
2107
        'teaser' => array(
2108
          'type' => 'field_test_default',
2109
          'settings' => array(
2110
            'test_formatter_setting' => $this->randomName(),
2111
          ),
2112
        ),
2113
      ),
2114
    );
2115
    field_create_field($this->field);
2116
    field_create_instance($this->instance);
2117

    
2118
    // Create an entity with values.
2119
    $this->values = $this->_generateTestFieldValues($this->cardinality);
2120
    $this->entity = field_test_create_stub_entity();
2121
    $this->is_new = TRUE;
2122
    $this->entity->{$this->field_name}[LANGUAGE_NONE] = $this->values;
2123
    field_test_entity_save($this->entity);
2124
  }
2125

    
2126
  /**
2127
   * Test the field_view_field() function.
2128
   */
2129
  function testFieldViewField() {
2130
    // No display settings: check that default display settings are used.
2131
    $output = field_view_field('test_entity', $this->entity, $this->field_name);
2132
    $this->drupalSetContent(drupal_render($output));
2133
    $settings = field_info_formatter_settings('field_test_default');
2134
    $setting = $settings['test_formatter_setting'];
2135
    $this->assertText($this->label, 'Label was displayed.');
2136
    foreach ($this->values as $delta => $value) {
2137
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2138
    }
2139

    
2140
    // Check that explicit display settings are used.
2141
    $display = array(
2142
      'label' => 'hidden',
2143
      'type' => 'field_test_multiple',
2144
      'settings' => array(
2145
        'test_formatter_setting_multiple' => $this->randomName(),
2146
        'alter' => TRUE,
2147
      ),
2148
    );
2149
    $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
2150
    $this->drupalSetContent(drupal_render($output));
2151
    $setting = $display['settings']['test_formatter_setting_multiple'];
2152
    $this->assertNoText($this->label, 'Label was not displayed.');
2153
    $this->assertText('field_test_field_attach_view_alter', 'Alter fired, display passed.');
2154
    $array = array();
2155
    foreach ($this->values as $delta => $value) {
2156
      $array[] = $delta . ':' . $value['value'];
2157
    }
2158
    $this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
2159

    
2160
    // Check the prepare_view steps are invoked.
2161
    $display = array(
2162
      'label' => 'hidden',
2163
      'type' => 'field_test_with_prepare_view',
2164
      'settings' => array(
2165
        'test_formatter_setting_additional' => $this->randomName(),
2166
      ),
2167
    );
2168
    $output = field_view_field('test_entity', $this->entity, $this->field_name, $display);
2169
    $view = drupal_render($output);
2170
    $this->drupalSetContent($view);
2171
    $setting = $display['settings']['test_formatter_setting_additional'];
2172
    $this->assertNoText($this->label, 'Label was not displayed.');
2173
    $this->assertNoText('field_test_field_attach_view_alter', 'Alter not fired.');
2174
    foreach ($this->values as $delta => $value) {
2175
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2176
    }
2177

    
2178
    // View mode: check that display settings specified in the instance are
2179
    // used.
2180
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'teaser');
2181
    $this->drupalSetContent(drupal_render($output));
2182
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
2183
    $this->assertText($this->label, 'Label was displayed.');
2184
    foreach ($this->values as $delta => $value) {
2185
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2186
    }
2187

    
2188
    // Unknown view mode: check that display settings for 'default' view mode
2189
    // are used.
2190
    $output = field_view_field('test_entity', $this->entity, $this->field_name, 'unknown_view_mode');
2191
    $this->drupalSetContent(drupal_render($output));
2192
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
2193
    $this->assertText($this->label, 'Label was displayed.');
2194
    foreach ($this->values as $delta => $value) {
2195
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2196
    }
2197
  }
2198

    
2199
  /**
2200
   * Test the field_view_value() function.
2201
   */
2202
  function testFieldViewValue() {
2203
    // No display settings: check that default display settings are used.
2204
    $settings = field_info_formatter_settings('field_test_default');
2205
    $setting = $settings['test_formatter_setting'];
2206
    foreach ($this->values as $delta => $value) {
2207
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2208
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item);
2209
      $this->drupalSetContent(drupal_render($output));
2210
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2211
    }
2212

    
2213
    // Check that explicit display settings are used.
2214
    $display = array(
2215
      'type' => 'field_test_multiple',
2216
      'settings' => array(
2217
        'test_formatter_setting_multiple' => $this->randomName(),
2218
      ),
2219
    );
2220
    $setting = $display['settings']['test_formatter_setting_multiple'];
2221
    $array = array();
2222
    foreach ($this->values as $delta => $value) {
2223
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2224
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
2225
      $this->drupalSetContent(drupal_render($output));
2226
      $this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2227
    }
2228

    
2229
    // Check that prepare_view steps are invoked.
2230
    $display = array(
2231
      'type' => 'field_test_with_prepare_view',
2232
      'settings' => array(
2233
        'test_formatter_setting_additional' => $this->randomName(),
2234
      ),
2235
    );
2236
    $setting = $display['settings']['test_formatter_setting_additional'];
2237
    $array = array();
2238
    foreach ($this->values as $delta => $value) {
2239
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2240
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, $display);
2241
      $this->drupalSetContent(drupal_render($output));
2242
      $this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2243
    }
2244

    
2245
    // View mode: check that display settings specified in the instance are
2246
    // used.
2247
    $setting = $this->instance['display']['teaser']['settings']['test_formatter_setting'];
2248
    foreach ($this->values as $delta => $value) {
2249
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2250
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'teaser');
2251
      $this->drupalSetContent(drupal_render($output));
2252
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2253
    }
2254

    
2255
    // Unknown view mode: check that display settings for 'default' view mode
2256
    // are used.
2257
    $setting = $this->instance['display']['default']['settings']['test_formatter_setting'];
2258
    foreach ($this->values as $delta => $value) {
2259
      $item = $this->entity->{$this->field_name}[LANGUAGE_NONE][$delta];
2260
      $output = field_view_value('test_entity', $this->entity, $this->field_name, $item, 'unknown_view_mode');
2261
      $this->drupalSetContent(drupal_render($output));
2262
      $this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
2263
    }
2264
  }
2265
}
2266

    
2267
class FieldCrudTestCase extends FieldTestCase {
2268
  public static function getInfo() {
2269
    return array(
2270
      'name' => 'Field CRUD tests',
2271
      'description' => 'Test field create, read, update, and delete.',
2272
      'group' => 'Field API',
2273
    );
2274
  }
2275

    
2276
  function setUp() {
2277
    // field_update_field() tests use number.module
2278
    parent::setUp('field_test', 'number');
2279
  }
2280

    
2281
  // TODO : test creation with
2282
  // - a full fledged $field structure, check that all the values are there
2283
  // - a minimal $field structure, check all default values are set
2284
  // defer actual $field comparison to a helper function, used for the two cases above
2285

    
2286
  /**
2287
   * Test the creation of a field.
2288
   */
2289
  function testCreateField() {
2290
    $field_definition = array(
2291
      'field_name' => 'field_2',
2292
      'type' => 'test_field',
2293
    );
2294
    field_test_memorize();
2295
    $field_definition = field_create_field($field_definition);
2296
    $mem = field_test_memorize();
2297
    $this->assertIdentical($mem['field_test_field_create_field'][0][0], $field_definition, 'hook_field_create_field() called with correct arguments.');
2298

    
2299
    // Read the raw record from the {field_config_instance} table.
2300
    $result = db_query('SELECT * FROM {field_config} WHERE field_name = :field_name', array(':field_name' => $field_definition['field_name']));
2301
    $record = $result->fetchAssoc();
2302
    $record['data'] = unserialize($record['data']);
2303

    
2304
    // Ensure that basic properties are preserved.
2305
    $this->assertEqual($record['field_name'], $field_definition['field_name'], 'The field name is properly saved.');
2306
    $this->assertEqual($record['type'], $field_definition['type'], 'The field type is properly saved.');
2307

    
2308
    // Ensure that cardinality defaults to 1.
2309
    $this->assertEqual($record['cardinality'], 1, 'Cardinality defaults to 1.');
2310

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

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

    
2318
    // Guarantee that the name is unique.
2319
    try {
2320
      field_create_field($field_definition);
2321
      $this->fail(t('Cannot create two fields with the same name.'));
2322
    }
2323
    catch (FieldException $e) {
2324
      $this->pass(t('Cannot create two fields with the same name.'));
2325
    }
2326

    
2327
    // Check that field type is required.
2328
    try {
2329
      $field_definition = array(
2330
        'field_name' => 'field_1',
2331
      );
2332
      field_create_field($field_definition);
2333
      $this->fail(t('Cannot create a field with no type.'));
2334
    }
2335
    catch (FieldException $e) {
2336
      $this->pass(t('Cannot create a field with no type.'));
2337
    }
2338

    
2339
    // Check that field name is required.
2340
    try {
2341
      $field_definition = array(
2342
        'type' => 'test_field'
2343
      );
2344
      field_create_field($field_definition);
2345
      $this->fail(t('Cannot create an unnamed field.'));
2346
    }
2347
    catch (FieldException $e) {
2348
      $this->pass(t('Cannot create an unnamed field.'));
2349
    }
2350

    
2351
    // Check that field name must start with a letter or _.
2352
    try {
2353
      $field_definition = array(
2354
        'field_name' => '2field_2',
2355
        'type' => 'test_field',
2356
      );
2357
      field_create_field($field_definition);
2358
      $this->fail(t('Cannot create a field with a name starting with a digit.'));
2359
    }
2360
    catch (FieldException $e) {
2361
      $this->pass(t('Cannot create a field with a name starting with a digit.'));
2362
    }
2363

    
2364
    // Check that field name must only contain lowercase alphanumeric or _.
2365
    try {
2366
      $field_definition = array(
2367
        'field_name' => 'field#_3',
2368
        'type' => 'test_field',
2369
      );
2370
      field_create_field($field_definition);
2371
      $this->fail(t('Cannot create a field with a name containing an illegal character.'));
2372
    }
2373
    catch (FieldException $e) {
2374
      $this->pass(t('Cannot create a field with a name containing an illegal character.'));
2375
    }
2376

    
2377
    // Check that field name cannot be longer than 32 characters long.
2378
    try {
2379
      $field_definition = array(
2380
        'field_name' => '_12345678901234567890123456789012',
2381
        'type' => 'test_field',
2382
      );
2383
      field_create_field($field_definition);
2384
      $this->fail(t('Cannot create a field with a name longer than 32 characters.'));
2385
    }
2386
    catch (FieldException $e) {
2387
      $this->pass(t('Cannot create a field with a name longer than 32 characters.'));
2388
    }
2389

    
2390
    // Check that field name can not be an entity key.
2391
    // "ftvid" is known as an entity key from the "test_entity" type.
2392
    try {
2393
      $field_definition = array(
2394
        'type' => 'test_field',
2395
        'field_name' => 'ftvid',
2396
      );
2397
      $field = field_create_field($field_definition);
2398
      $this->fail(t('Cannot create a field bearing the name of an entity key.'));
2399
    }
2400
    catch (FieldException $e) {
2401
      $this->pass(t('Cannot create a field bearing the name of an entity key.'));
2402
    }
2403
  }
2404

    
2405
  /**
2406
   * Test failure to create a field.
2407
   */
2408
  function testCreateFieldFail() {
2409
    $field_name = 'duplicate';
2410
    $field_definition = array('field_name' => $field_name, 'type' => 'test_field', 'storage' => array('type' => 'field_test_storage_failure'));
2411
    $query = db_select('field_config')->condition('field_name', $field_name)->countQuery();
2412

    
2413
    // The field does not appear in field_config.
2414
    $count = $query->execute()->fetchField();
2415
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
2416

    
2417
    // Try to create the field.
2418
    try {
2419
      $field = field_create_field($field_definition);
2420
      $this->assertTrue(FALSE, 'Field creation (correctly) fails.');
2421
    }
2422
    catch (Exception $e) {
2423
      $this->assertTrue(TRUE, 'Field creation (correctly) fails.');
2424
    }
2425

    
2426
    // The field does not appear in field_config.
2427
    $count = $query->execute()->fetchField();
2428
    $this->assertEqual($count, 0, 'A field_config row for the field does not exist.');
2429
  }
2430

    
2431
  /**
2432
   * Test reading back a field definition.
2433
   */
2434
  function testReadField() {
2435
    $field_definition = array(
2436
      'field_name' => 'field_1',
2437
      'type' => 'test_field',
2438
    );
2439
    field_create_field($field_definition);
2440

    
2441
    // Read the field back.
2442
    $field = field_read_field($field_definition['field_name']);
2443
    $this->assertTrue($field_definition < $field, 'The field was properly read.');
2444
  }
2445

    
2446
  /**
2447
   * Tests reading field definitions.
2448
   */
2449
  function testReadFields() {
2450
    $field_definition = array(
2451
      'field_name' => 'field_1',
2452
      'type' => 'test_field',
2453
    );
2454
    field_create_field($field_definition);
2455

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

    
2460
    // Check that 'multi column' criteria works.
2461
    $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => $field_definition['type']));
2462
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2463
    $fields = field_read_fields(array('field_name' => $field_definition['field_name'], 'type' => 'foo'));
2464
    $this->assertTrue(empty($fields), 'No field was found.');
2465

    
2466
    // Create an instance of the field.
2467
    $instance_definition = array(
2468
      'field_name' => $field_definition['field_name'],
2469
      'entity_type' => 'test_entity',
2470
      'bundle' => 'test_bundle',
2471
    );
2472
    field_create_instance($instance_definition);
2473

    
2474
    // Check that criteria spanning over the field_config_instance table work.
2475
    $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'bundle' => $instance_definition['bundle']));
2476
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2477
    $fields = field_read_fields(array('entity_type' => $instance_definition['entity_type'], 'field_name' => $instance_definition['field_name']));
2478
    $this->assertTrue(count($fields) == 1 && isset($fields[$field_definition['field_name']]), 'The field was properly read.');
2479
  }
2480

    
2481
  /**
2482
   * Test creation of indexes on data column.
2483
   */
2484
  function testFieldIndexes() {
2485
    // Check that indexes specified by the field type are used by default.
2486
    $field_definition = array(
2487
      'field_name' => 'field_1',
2488
      'type' => 'test_field',
2489
    );
2490
    field_create_field($field_definition);
2491
    $field = field_read_field($field_definition['field_name']);
2492
    $expected_indexes = array('value' => array('value'));
2493
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field type indexes saved by default');
2494

    
2495
    // Check that indexes specified by the field definition override the field
2496
    // type indexes.
2497
    $field_definition = array(
2498
      'field_name' => 'field_2',
2499
      'type' => 'test_field',
2500
      'indexes' => array(
2501
        'value' => array(),
2502
      ),
2503
    );
2504
    field_create_field($field_definition);
2505
    $field = field_read_field($field_definition['field_name']);
2506
    $expected_indexes = array('value' => array());
2507
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes override field type indexes');
2508

    
2509
    // Check that indexes specified by the field definition add to the field
2510
    // type indexes.
2511
    $field_definition = array(
2512
      'field_name' => 'field_3',
2513
      'type' => 'test_field',
2514
      'indexes' => array(
2515
        'value_2' => array('value'),
2516
      ),
2517
    );
2518
    field_create_field($field_definition);
2519
    $field = field_read_field($field_definition['field_name']);
2520
    $expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
2521
    $this->assertEqual($field['indexes'], $expected_indexes, 'Field definition indexes are merged with field type indexes');
2522
  }
2523

    
2524
  /**
2525
   * Test the deletion of a field.
2526
   */
2527
  function testDeleteField() {
2528
    // TODO: Also test deletion of the data stored in the field ?
2529

    
2530
    // Create two fields (so we can test that only one is deleted).
2531
    $this->field = array('field_name' => 'field_1', 'type' => 'test_field');
2532
    field_create_field($this->field);
2533
    $this->another_field = array('field_name' => 'field_2', 'type' => 'test_field');
2534
    field_create_field($this->another_field);
2535

    
2536
    // Create instances for each.
2537
    $this->instance_definition = array(
2538
      'field_name' => $this->field['field_name'],
2539
      'entity_type' => 'test_entity',
2540
      'bundle' => 'test_bundle',
2541
      'widget' => array(
2542
        'type' => 'test_field_widget',
2543
      ),
2544
    );
2545
    field_create_instance($this->instance_definition);
2546
    $this->another_instance_definition = $this->instance_definition;
2547
    $this->another_instance_definition['field_name'] = $this->another_field['field_name'];
2548
    field_create_instance($this->another_instance_definition);
2549

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

    
2555
    // Make sure that the field is marked as deleted when it is specifically
2556
    // loaded.
2557
    $field = field_read_field($this->field['field_name'], array('include_deleted' => TRUE));
2558
    $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion.');
2559

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

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

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

    
2573
    // Make sure the other field (and its field instance) are not deleted.
2574
    $another_field = field_read_field($this->another_field['field_name']);
2575
    $this->assertTrue(!empty($another_field) && empty($another_field['deleted']), 'A non-deleted field is not marked for deletion.');
2576
    $another_instance = field_read_instance('test_entity', $this->another_instance_definition['field_name'], $this->another_instance_definition['bundle']);
2577
    $this->assertTrue(!empty($another_instance) && empty($another_instance['deleted']), 'An instance of a non-deleted field is not marked for deletion.');
2578

    
2579
    // Try to create a new field the same name as a deleted field and
2580
    // write data into it.
2581
    field_create_field($this->field);
2582
    field_create_instance($this->instance_definition);
2583
    $field = field_read_field($this->field['field_name']);
2584
    $this->assertTrue(!empty($field) && empty($field['deleted']), 'A new field with a previously used name is created.');
2585
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2586
    $this->assertTrue(!empty($instance) && empty($instance['deleted']), 'A new instance for a previously used field name is created.');
2587

    
2588
    // Save an entity with data for the field
2589
    $entity = field_test_create_stub_entity(0, 0, $instance['bundle']);
2590
    $langcode = LANGUAGE_NONE;
2591
    $values[0]['value'] = mt_rand(1, 127);
2592
    $entity->{$field['field_name']}[$langcode] = $values;
2593
    $entity_type = 'test_entity';
2594
    field_attach_insert('test_entity', $entity);
2595

    
2596
    // Verify the field is present on load
2597
    $entity = field_test_create_stub_entity(0, 0, $this->instance_definition['bundle']);
2598
    field_attach_load($entity_type, array(0 => $entity));
2599
    $this->assertIdentical(count($entity->{$field['field_name']}[$langcode]), count($values), "Data in previously deleted field saves and loads correctly");
2600
    foreach ($values as $delta => $value) {
2601
      $this->assertEqual($entity->{$field['field_name']}[$langcode][$delta]['value'], $values[$delta]['value'], "Data in previously deleted field saves and loads correctly");
2602
    }
2603
  }
2604

    
2605
  function testUpdateNonExistentField() {
2606
    $test_field = array('field_name' => 'does_not_exist', 'type' => 'number_decimal');
2607
    try {
2608
      field_update_field($test_field);
2609
      $this->fail(t('Cannot update a field that does not exist.'));
2610
    }
2611
    catch (FieldException $e) {
2612
      $this->pass(t('Cannot update a field that does not exist.'));
2613
    }
2614
  }
2615

    
2616
  function testUpdateFieldType() {
2617
    $field = array('field_name' => 'field_type', 'type' => 'number_decimal');
2618
    $field = field_create_field($field);
2619

    
2620
    $test_field = array('field_name' => 'field_type', 'type' => 'number_integer');
2621
    try {
2622
      field_update_field($test_field);
2623
      $this->fail(t('Cannot update a field to a different type.'));
2624
    }
2625
    catch (FieldException $e) {
2626
      $this->pass(t('Cannot update a field to a different type.'));
2627
    }
2628
  }
2629

    
2630
  /**
2631
   * Test updating a field.
2632
   */
2633
  function testUpdateField() {
2634
    // Create a field with a defined cardinality, so that we can ensure it's
2635
    // respected. Since cardinality enforcement is consistent across database
2636
    // systems, it makes a good test case.
2637
    $cardinality = 4;
2638
    $field_definition = array(
2639
      'field_name' => 'field_update',
2640
      'type' => 'test_field',
2641
      'cardinality' => $cardinality,
2642
    );
2643
    $field_definition = field_create_field($field_definition);
2644
    $instance = array(
2645
      'field_name' => 'field_update',
2646
      'entity_type' => 'test_entity',
2647
      'bundle' => 'test_bundle',
2648
    );
2649
    $instance = field_create_instance($instance);
2650

    
2651
    do {
2652
      // We need a unique ID for our entity. $cardinality will do.
2653
      $id = $cardinality;
2654
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
2655
      // Fill in the entity with more values than $cardinality.
2656
      for ($i = 0; $i < 20; $i++) {
2657
        $entity->field_update[LANGUAGE_NONE][$i]['value'] = $i;
2658
      }
2659
      // Save the entity.
2660
      field_attach_insert('test_entity', $entity);
2661
      // Load back and assert there are $cardinality number of values.
2662
      $entity = field_test_create_stub_entity($id, $id, $instance['bundle']);
2663
      field_attach_load('test_entity', array($id => $entity));
2664
      $this->assertEqual(count($entity->field_update[LANGUAGE_NONE]), $field_definition['cardinality'], 'Cardinality is kept');
2665
      // Now check the values themselves.
2666
      for ($delta = 0; $delta < $cardinality; $delta++) {
2667
        $this->assertEqual($entity->field_update[LANGUAGE_NONE][$delta]['value'], $delta, 'Value is kept');
2668
      }
2669
      // Increase $cardinality and set the field cardinality to the new value.
2670
      $field_definition['cardinality'] = ++$cardinality;
2671
      field_update_field($field_definition);
2672
    } while ($cardinality < 6);
2673
  }
2674

    
2675
  /**
2676
   * Test field type modules forbidding an update.
2677
   */
2678
  function testUpdateFieldForbid() {
2679
    $field = array('field_name' => 'forbidden', 'type' => 'test_field', 'settings' => array('changeable' => 0, 'unchangeable' => 0));
2680
    $field = field_create_field($field);
2681
    $field['settings']['changeable']++;
2682
    try {
2683
      field_update_field($field);
2684
      $this->pass(t("A changeable setting can be updated."));
2685
    }
2686
    catch (FieldException $e) {
2687
      $this->fail(t("An unchangeable setting cannot be updated."));
2688
    }
2689
    $field['settings']['unchangeable']++;
2690
    try {
2691
      field_update_field($field);
2692
      $this->fail(t("An unchangeable setting can be updated."));
2693
    }
2694
    catch (FieldException $e) {
2695
      $this->pass(t("An unchangeable setting cannot be updated."));
2696
    }
2697
  }
2698

    
2699
  /**
2700
   * Test that fields are properly marked active or inactive.
2701
   */
2702
  function testActive() {
2703
    $field_definition = array(
2704
      'field_name' => 'field_1',
2705
      'type' => 'test_field',
2706
      // For this test, we need a storage backend provided by a different
2707
      // module than field_test.module.
2708
      'storage' => array(
2709
        'type' => 'field_sql_storage',
2710
      ),
2711
    );
2712
    field_create_field($field_definition);
2713

    
2714
    // Test disabling and enabling:
2715
    // - the field type module,
2716
    // - the storage module,
2717
    // - both.
2718
    $this->_testActiveHelper($field_definition, array('field_test'));
2719
    $this->_testActiveHelper($field_definition, array('field_sql_storage'));
2720
    $this->_testActiveHelper($field_definition, array('field_test', 'field_sql_storage'));
2721
  }
2722

    
2723
  /**
2724
   * Helper function for testActive().
2725
   *
2726
   * Test dependency between a field and a set of modules.
2727
   *
2728
   * @param $field_definition
2729
   *   A field definition.
2730
   * @param $modules
2731
   *   An aray of module names. The field will be tested to be inactive as long
2732
   *   as any of those modules is disabled.
2733
   */
2734
  function _testActiveHelper($field_definition, $modules) {
2735
    $field_name = $field_definition['field_name'];
2736

    
2737
    // Read the field.
2738
    $field = field_read_field($field_name);
2739
    $this->assertTrue($field_definition <= $field, 'The field was properly read.');
2740

    
2741
    module_disable($modules, FALSE);
2742

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

    
2746
    // Re-enable modules one by one, and check that the field is still inactive
2747
    // while some modules remain disabled.
2748
    while ($modules) {
2749
      $field = field_read_field($field_name);
2750
      $this->assertTrue(empty($field), format_string('%modules disabled. The field is marked inactive.', array('%modules' => implode(', ', $modules))));
2751

    
2752
      $module = array_shift($modules);
2753
      module_enable(array($module), FALSE);
2754
    }
2755

    
2756
    // Check that the field is active again after all modules have been
2757
    // enabled.
2758
    $field = field_read_field($field_name);
2759
    $this->assertTrue($field_definition <= $field, 'The field was was marked active.');
2760
  }
2761
}
2762

    
2763
class FieldInstanceCrudTestCase extends FieldTestCase {
2764
  protected $field;
2765

    
2766
  public static function getInfo() {
2767
    return array(
2768
      'name' => 'Field instance CRUD tests',
2769
      'description' => 'Create field entities by attaching fields to entities.',
2770
      'group' => 'Field API',
2771
    );
2772
  }
2773

    
2774
  function setUp() {
2775
    parent::setUp('field_test');
2776

    
2777
    $this->field = array(
2778
      'field_name' => drupal_strtolower($this->randomName()),
2779
      'type' => 'test_field',
2780
    );
2781
    field_create_field($this->field);
2782
    $this->instance_definition = array(
2783
      'field_name' => $this->field['field_name'],
2784
      'entity_type' => 'test_entity',
2785
      'bundle' => 'test_bundle',
2786
    );
2787
  }
2788

    
2789
  // TODO : test creation with
2790
  // - a full fledged $instance structure, check that all the values are there
2791
  // - a minimal $instance structure, check all default values are set
2792
  // defer actual $instance comparison to a helper function, used for the two cases above,
2793
  // and for testUpdateFieldInstance
2794

    
2795
  /**
2796
   * Test the creation of a field instance.
2797
   */
2798
  function testCreateFieldInstance() {
2799
    field_create_instance($this->instance_definition);
2800

    
2801
    // Read the raw record from the {field_config_instance} table.
2802
    $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']));
2803
    $record = $result->fetchAssoc();
2804
    $record['data'] = unserialize($record['data']);
2805

    
2806
    $field_type = field_info_field_types($this->field['type']);
2807
    $widget_type = field_info_widget_types($field_type['default_widget']);
2808
    $formatter_type = field_info_formatter_types($field_type['default_formatter']);
2809

    
2810
    // Check that default values are set.
2811
    $this->assertIdentical($record['data']['required'], FALSE, 'Required defaults to false.');
2812
    $this->assertIdentical($record['data']['label'], $this->instance_definition['field_name'], 'Label defaults to field name.');
2813
    $this->assertIdentical($record['data']['description'], '', 'Description defaults to empty string.');
2814
    $this->assertIdentical($record['data']['widget']['type'], $field_type['default_widget'], 'Default widget has been written.');
2815
    $this->assertTrue(isset($record['data']['display']['default']), 'Display for "full" view_mode has been written.');
2816
    $this->assertIdentical($record['data']['display']['default']['type'], $field_type['default_formatter'], 'Default formatter for "full" view_mode has been written.');
2817

    
2818
    // Check that default settings are set.
2819
    $this->assertIdentical($record['data']['settings'], $field_type['instance_settings'] , 'Default instance settings have been written.');
2820
    $this->assertIdentical($record['data']['widget']['settings'], $widget_type['settings'] , 'Default widget settings have been written.');
2821
    $this->assertIdentical($record['data']['display']['default']['settings'], $formatter_type['settings'], 'Default formatter settings for "full" view_mode have been written.');
2822

    
2823
    // Guarantee that the field/bundle combination is unique.
2824
    try {
2825
      field_create_instance($this->instance_definition);
2826
      $this->fail(t('Cannot create two instances with the same field / bundle combination.'));
2827
    }
2828
    catch (FieldException $e) {
2829
      $this->pass(t('Cannot create two instances with the same field / bundle combination.'));
2830
    }
2831

    
2832
    // Check that the specified field exists.
2833
    try {
2834
      $this->instance_definition['field_name'] = $this->randomName();
2835
      field_create_instance($this->instance_definition);
2836
      $this->fail(t('Cannot create an instance of a non-existing field.'));
2837
    }
2838
    catch (FieldException $e) {
2839
      $this->pass(t('Cannot create an instance of a non-existing field.'));
2840
    }
2841

    
2842
    // Create a field restricted to a specific entity type.
2843
    $field_restricted = array(
2844
      'field_name' => drupal_strtolower($this->randomName()),
2845
      'type' => 'test_field',
2846
      'entity_types' => array('test_cacheable_entity'),
2847
    );
2848
    field_create_field($field_restricted);
2849

    
2850
    // Check that an instance can be added to an entity type allowed
2851
    // by the field.
2852
    try {
2853
      $instance = $this->instance_definition;
2854
      $instance['field_name'] = $field_restricted['field_name'];
2855
      $instance['entity_type'] = 'test_cacheable_entity';
2856
      field_create_instance($instance);
2857
      $this->pass(t('Can create an instance on an entity type allowed by the field.'));
2858
    }
2859
    catch (FieldException $e) {
2860
      $this->fail(t('Can create an instance on an entity type allowed by the field.'));
2861
    }
2862

    
2863
    // Check that an instance cannot be added to an entity type
2864
    // forbidden by the field.
2865
    try {
2866
      $instance = $this->instance_definition;
2867
      $instance['field_name'] = $field_restricted['field_name'];
2868
      field_create_instance($instance);
2869
      $this->fail(t('Cannot create an instance on an entity type forbidden by the field.'));
2870
    }
2871
    catch (FieldException $e) {
2872
      $this->pass(t('Cannot create an instance on an entity type forbidden by the field.'));
2873
    }
2874

    
2875
    // TODO: test other failures.
2876
  }
2877

    
2878
  /**
2879
   * Test reading back an instance definition.
2880
   */
2881
  function testReadFieldInstance() {
2882
    field_create_instance($this->instance_definition);
2883

    
2884
    // Read the instance back.
2885
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2886
    $this->assertTrue($this->instance_definition < $instance, 'The field was properly read.');
2887
  }
2888

    
2889
  /**
2890
   * Test the update of a field instance.
2891
   */
2892
  function testUpdateFieldInstance() {
2893
    field_create_instance($this->instance_definition);
2894
    $field_type = field_info_field_types($this->field['type']);
2895

    
2896
    // Check that basic changes are saved.
2897
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2898
    $instance['required'] = !$instance['required'];
2899
    $instance['label'] = $this->randomName();
2900
    $instance['description'] = $this->randomName();
2901
    $instance['settings']['test_instance_setting'] = $this->randomName();
2902
    $instance['widget']['settings']['test_widget_setting'] =$this->randomName();
2903
    $instance['widget']['weight']++;
2904
    $instance['display']['default']['settings']['test_formatter_setting'] = $this->randomName();
2905
    $instance['display']['default']['weight']++;
2906
    field_update_instance($instance);
2907

    
2908
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2909
    $this->assertEqual($instance['required'], $instance_new['required'], '"required" change is saved');
2910
    $this->assertEqual($instance['label'], $instance_new['label'], '"label" change is saved');
2911
    $this->assertEqual($instance['description'], $instance_new['description'], '"description" change is saved');
2912
    $this->assertEqual($instance['widget']['settings']['test_widget_setting'], $instance_new['widget']['settings']['test_widget_setting'], 'Widget setting change is saved');
2913
    $this->assertEqual($instance['widget']['weight'], $instance_new['widget']['weight'], 'Widget weight change is saved');
2914
    $this->assertEqual($instance['display']['default']['settings']['test_formatter_setting'], $instance_new['display']['default']['settings']['test_formatter_setting'], 'Formatter setting change is saved');
2915
    $this->assertEqual($instance['display']['default']['weight'], $instance_new['display']['default']['weight'], 'Widget weight change is saved');
2916

    
2917
    // Check that changing widget and formatter types updates the default settings.
2918
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2919
    $instance['widget']['type'] = 'test_field_widget_multiple';
2920
    $instance['display']['default']['type'] = 'field_test_multiple';
2921
    field_update_instance($instance);
2922

    
2923
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2924
    $this->assertEqual($instance['widget']['type'], $instance_new['widget']['type'] , 'Widget type change is saved.');
2925
    $settings = field_info_widget_settings($instance_new['widget']['type']);
2926
    $this->assertIdentical($settings, array_intersect_key($instance_new['widget']['settings'], $settings) , 'Widget type change updates default settings.');
2927
    $this->assertEqual($instance['display']['default']['type'], $instance_new['display']['default']['type'] , 'Formatter type change is saved.');
2928
    $info = field_info_formatter_types($instance_new['display']['default']['type']);
2929
    $settings = $info['settings'];
2930
    $this->assertIdentical($settings, array_intersect_key($instance_new['display']['default']['settings'], $settings) , 'Changing formatter type updates default settings.');
2931

    
2932
    // Check that adding a new view mode is saved and gets default settings.
2933
    $instance = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2934
    $instance['display']['teaser'] = array();
2935
    field_update_instance($instance);
2936

    
2937
    $instance_new = field_read_instance('test_entity', $this->instance_definition['field_name'], $this->instance_definition['bundle']);
2938
    $this->assertTrue(isset($instance_new['display']['teaser']), 'Display for the new view_mode has been written.');
2939
    $this->assertIdentical($instance_new['display']['teaser']['type'], $field_type['default_formatter'], 'Default formatter for the new view_mode has been written.');
2940
    $info = field_info_formatter_types($instance_new['display']['teaser']['type']);
2941
    $settings = $info['settings'];
2942
    $this->assertIdentical($settings, $instance_new['display']['teaser']['settings'] , 'Default formatter settings for the new view_mode have been written.');
2943

    
2944
    // TODO: test failures.
2945
  }
2946

    
2947
  /**
2948
   * Test the deletion of a field instance.
2949
   */
2950
  function testDeleteFieldInstance() {
2951
    // TODO: Test deletion of the data stored in the field also.
2952
    // Need to check that data for a 'deleted' field / instance doesn't get loaded
2953
    // Need to check data marked deleted is cleaned on cron (not implemented yet...)
2954

    
2955
    // Create two instances for the same field so we can test that only one
2956
    // is deleted.
2957
    field_create_instance($this->instance_definition);
2958
    $this->another_instance_definition = $this->instance_definition;
2959
    $this->another_instance_definition['bundle'] .= '_another_bundle';
2960
    $instance = field_create_instance($this->another_instance_definition);
2961

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

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

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

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

    
2980
    // Make sure the field is deleted when its last instance is deleted.
2981
    field_delete_instance($another_instance);
2982
    $field = field_read_field($another_instance['field_name'], array('include_deleted' => TRUE));
2983
    $this->assertTrue(!empty($field['deleted']), 'A deleted field is marked for deletion after all its instances have been marked for deletion.');
2984
  }
2985
}
2986

    
2987
/**
2988
 * Unit test class for the multilanguage fields logic.
2989
 *
2990
 * The following tests will check the multilanguage logic of _field_invoke() and
2991
 * that only the correct values are returned by field_available_languages().
2992
 */
2993
class FieldTranslationsTestCase extends FieldTestCase {
2994
  public static function getInfo() {
2995
    return array(
2996
      'name' => 'Field translations tests',
2997
      'description' => 'Test multilanguage fields logic.',
2998
      'group' => 'Field API',
2999
    );
3000
  }
3001

    
3002
  function setUp() {
3003
    parent::setUp('locale', 'field_test');
3004

    
3005
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
3006

    
3007
    $this->entity_type = 'test_entity';
3008

    
3009
    $field = array(
3010
      'field_name' => $this->field_name,
3011
      'type' => 'test_field',
3012
      'cardinality' => 4,
3013
      'translatable' => TRUE,
3014
    );
3015
    field_create_field($field);
3016
    $this->field = field_read_field($this->field_name);
3017

    
3018
    $instance = array(
3019
      'field_name' => $this->field_name,
3020
      'entity_type' => $this->entity_type,
3021
      'bundle' => 'test_bundle',
3022
    );
3023
    field_create_instance($instance);
3024
    $this->instance = field_read_instance('test_entity', $this->field_name, 'test_bundle');
3025

    
3026
    require_once DRUPAL_ROOT . '/includes/locale.inc';
3027
    for ($i = 0; $i < 3; ++$i) {
3028
      locale_add_language('l' . $i, $this->randomString(), $this->randomString());
3029
    }
3030
  }
3031

    
3032
  /**
3033
   * Ensures that only valid values are returned by field_available_languages().
3034
   */
3035
  function testFieldAvailableLanguages() {
3036
    // Test 'translatable' fieldable info.
3037
    field_test_entity_info_translatable('test_entity', FALSE);
3038
    $field = $this->field;
3039
    $field['field_name'] .= '_untranslatable';
3040

    
3041
    // Enable field translations for the entity.
3042
    field_test_entity_info_translatable('test_entity', TRUE);
3043

    
3044
    // Test hook_field_languages() invocation on a translatable field.
3045
    variable_set('field_test_field_available_languages_alter', TRUE);
3046
    $enabled_languages = field_content_languages();
3047
    $available_languages = field_available_languages($this->entity_type, $this->field);
3048
    foreach ($available_languages as $delta => $langcode) {
3049
      if ($langcode != 'xx' && $langcode != 'en') {
3050
        $this->assertTrue(in_array($langcode, $enabled_languages), format_string('%language is an enabled language.', array('%language' => $langcode)));
3051
      }
3052
    }
3053
    $this->assertTrue(in_array('xx', $available_languages), format_string('%language was made available.', array('%language' => 'xx')));
3054
    $this->assertFalse(in_array('en', $available_languages), format_string('%language was made unavailable.', array('%language' => 'en')));
3055

    
3056
    // Test field_available_languages() behavior for untranslatable fields.
3057
    $this->field['translatable'] = FALSE;
3058
    field_update_field($this->field);
3059
    $available_languages = field_available_languages($this->entity_type, $this->field);
3060
    $this->assertTrue(count($available_languages) == 1 && $available_languages[0] === LANGUAGE_NONE, 'For untranslatable fields only LANGUAGE_NONE is available.');
3061
  }
3062

    
3063
  /**
3064
   * Test the multilanguage logic of _field_invoke().
3065
   */
3066
  function testFieldInvoke() {
3067
    // Enable field translations for the entity.
3068
    field_test_entity_info_translatable('test_entity', TRUE);
3069

    
3070
    $entity_type = 'test_entity';
3071
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
3072

    
3073
    // Populate some extra languages to check if _field_invoke() correctly uses
3074
    // the result of field_available_languages().
3075
    $values = array();
3076
    $extra_languages = mt_rand(1, 4);
3077
    $languages = $available_languages = field_available_languages($this->entity_type, $this->field);
3078
    for ($i = 0; $i < $extra_languages; ++$i) {
3079
      $languages[] = $this->randomName(2);
3080
    }
3081

    
3082
    // For each given language provide some random values.
3083
    foreach ($languages as $langcode) {
3084
      for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
3085
        $values[$langcode][$delta]['value'] = mt_rand(1, 127);
3086
      }
3087
    }
3088
    $entity->{$this->field_name} = $values;
3089

    
3090
    $results = _field_invoke('test_op', $entity_type, $entity);
3091
    foreach ($results as $langcode => $result) {
3092
      $hash = hash('sha256', serialize(array($entity_type, $entity, $this->field_name, $langcode, $values[$langcode])));
3093
      // Check whether the parameters passed to _field_invoke() were correctly
3094
      // forwarded to the callback function.
3095
      $this->assertEqual($hash, $result, format_string('The result for %language is correctly stored.', array('%language' => $langcode)));
3096
    }
3097

    
3098
    $this->assertEqual(count($results), count($available_languages), 'No unavailable language has been processed.');
3099
  }
3100

    
3101
  /**
3102
   * Test the multilanguage logic of _field_invoke_multiple().
3103
   */
3104
  function testFieldInvokeMultiple() {
3105
    // Enable field translations for the entity.
3106
    field_test_entity_info_translatable('test_entity', TRUE);
3107

    
3108
    $values = array();
3109
    $options = array();
3110
    $entities = array();
3111
    $entity_type = 'test_entity';
3112
    $entity_count = 5;
3113
    $available_languages = field_available_languages($this->entity_type, $this->field);
3114

    
3115
    for ($id = 1; $id <= $entity_count; ++$id) {
3116
      $entity = field_test_create_stub_entity($id, $id, $this->instance['bundle']);
3117
      $languages = $available_languages;
3118

    
3119
      // Populate some extra languages to check whether _field_invoke()
3120
      // correctly uses the result of field_available_languages().
3121
      $extra_languages = mt_rand(1, 4);
3122
      for ($i = 0; $i < $extra_languages; ++$i) {
3123
        $languages[] = $this->randomName(2);
3124
      }
3125

    
3126
      // For each given language provide some random values.
3127
      $language_count = count($languages);
3128
      for ($i = 0; $i < $language_count; ++$i) {
3129
        $langcode = $languages[$i];
3130
        // Avoid to populate at least one field translation to check that
3131
        // per-entity language suggestions work even when available field values
3132
        // are different for each language.
3133
        if ($i !== $id) {
3134
          for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
3135
            $values[$id][$langcode][$delta]['value'] = mt_rand(1, 127);
3136
          }
3137
        }
3138
        // Ensure that a language for which there is no field translation is
3139
        // used as display language to prepare per-entity language suggestions.
3140
        elseif (!isset($display_language)) {
3141
          $display_language = $langcode;
3142
        }
3143
      }
3144

    
3145
      $entity->{$this->field_name} = $values[$id];
3146
      $entities[$id] = $entity;
3147

    
3148
      // Store per-entity language suggestions.
3149
      $options['language'][$id] = field_language($entity_type, $entity, NULL, $display_language);
3150
    }
3151

    
3152
    $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities);
3153
    foreach ($grouped_results as $id => $results) {
3154
      foreach ($results as $langcode => $result) {
3155
        if (isset($values[$id][$langcode])) {
3156
          $hash = hash('sha256', serialize(array($entity_type, $entities[$id], $this->field_name, $langcode, $values[$id][$langcode])));
3157
          // Check whether the parameters passed to _field_invoke_multiple()
3158
          // were correctly forwarded to the callback function.
3159
          $this->assertEqual($hash, $result, format_string('The result for entity %id/%language is correctly stored.', array('%id' => $id, '%language' => $langcode)));
3160
        }
3161
      }
3162
      $this->assertEqual(count($results), count($available_languages), format_string('No unavailable language has been processed for entity %id.', array('%id' => $id)));
3163
    }
3164

    
3165
    $null = NULL;
3166
    $grouped_results = _field_invoke_multiple('test_op_multiple', $entity_type, $entities, $null, $null, $options);
3167
    foreach ($grouped_results as $id => $results) {
3168
      foreach ($results as $langcode => $result) {
3169
        $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)));
3170
      }
3171
    }
3172
  }
3173

    
3174
  /**
3175
   * Test translatable fields storage/retrieval.
3176
   */
3177
  function testTranslatableFieldSaveLoad() {
3178
    // Enable field translations for nodes.
3179
    field_test_entity_info_translatable('node', TRUE);
3180
    $entity_info = entity_get_info('node');
3181
    $this->assertTrue(count($entity_info['translation']), 'Nodes are translatable.');
3182

    
3183
    // Prepare the field translations.
3184
    field_test_entity_info_translatable('test_entity', TRUE);
3185
    $eid = $evid = 1;
3186
    $entity_type = 'test_entity';
3187
    $entity = field_test_create_stub_entity($eid, $evid, $this->instance['bundle']);
3188
    $field_translations = array();
3189
    $available_languages = field_available_languages($entity_type, $this->field);
3190
    $this->assertTrue(count($available_languages) > 1, 'Field is translatable.');
3191
    foreach ($available_languages as $langcode) {
3192
      $field_translations[$langcode] = $this->_generateTestFieldValues($this->field['cardinality']);
3193
    }
3194

    
3195
    // Save and reload the field translations.
3196
    $entity->{$this->field_name} = $field_translations;
3197
    field_attach_insert($entity_type, $entity);
3198
    unset($entity->{$this->field_name});
3199
    field_attach_load($entity_type, array($eid => $entity));
3200

    
3201
    // Check if the correct values were saved/loaded.
3202
    foreach ($field_translations as $langcode => $items) {
3203
      $result = TRUE;
3204
      foreach ($items as $delta => $item) {
3205
        $result = $result && $item['value'] == $entity->{$this->field_name}[$langcode][$delta]['value'];
3206
      }
3207
      $this->assertTrue($result, format_string('%language translation correctly handled.', array('%language' => $langcode)));
3208
    }
3209
  }
3210

    
3211
  /**
3212
   * Tests display language logic for translatable fields.
3213
   */
3214
  function testFieldDisplayLanguage() {
3215
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
3216
    $entity_type = 'test_entity';
3217

    
3218
    // We need an additional field here to properly test display language
3219
    // suggestions.
3220
    $field = array(
3221
      'field_name' => $field_name,
3222
      'type' => 'test_field',
3223
      'cardinality' => 2,
3224
      'translatable' => TRUE,
3225
    );
3226
    field_create_field($field);
3227

    
3228
    $instance = array(
3229
      'field_name' => $field['field_name'],
3230
      'entity_type' => $entity_type,
3231
      'bundle' => 'test_bundle',
3232
    );
3233
    field_create_instance($instance);
3234

    
3235
    $entity = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
3236
    $instances = field_info_instances($entity_type, $this->instance['bundle']);
3237

    
3238
    $enabled_languages = field_content_languages();
3239
    $languages = array();
3240

    
3241
    // Generate field translations for languages different from the first
3242
    // enabled.
3243
    foreach ($instances as $instance) {
3244
      $field_name = $instance['field_name'];
3245
      $field = field_info_field($field_name);
3246
      do {
3247
        // Index 0 is reserved for the requested language, this way we ensure
3248
        // that no field is actually populated with it.
3249
        $langcode = $enabled_languages[mt_rand(1, count($enabled_languages) - 1)];
3250
      }
3251
      while (isset($languages[$langcode]));
3252
      $languages[$langcode] = TRUE;
3253
      $entity->{$field_name}[$langcode] = $this->_generateTestFieldValues($field['cardinality']);
3254
    }
3255

    
3256
    // Test multiple-fields display languages for untranslatable entities.
3257
    field_test_entity_info_translatable($entity_type, FALSE);
3258
    drupal_static_reset('field_language');
3259
    $requested_language = $enabled_languages[0];
3260
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);
3261
    foreach ($instances as $instance) {
3262
      $field_name = $instance['field_name'];
3263
      $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)));
3264
    }
3265

    
3266
    // Test multiple-fields display languages for translatable entities.
3267
    field_test_entity_info_translatable($entity_type, TRUE);
3268
    drupal_static_reset('field_language');
3269
    $display_language = field_language($entity_type, $entity, NULL, $requested_language);
3270

    
3271
    foreach ($instances as $instance) {
3272
      $field_name = $instance['field_name'];
3273
      $langcode = $display_language[$field_name];
3274
      // As the requested language was not assinged to any field, if the
3275
      // returned language is defined for the current field, core fallback rules
3276
      // were successfully applied.
3277
      $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)));
3278
    }
3279

    
3280
    // Test single-field display language.
3281
    drupal_static_reset('field_language');
3282
    $langcode = field_language($entity_type, $entity, $this->field_name, $requested_language);
3283
    $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)));
3284

    
3285
    // Test field_language() basic behavior without language fallback.
3286
    variable_set('field_test_language_fallback', FALSE);
3287
    $entity->{$this->field_name}[$requested_language] = mt_rand(1, 127);
3288
    drupal_static_reset('field_language');
3289
    $display_language = field_language($entity_type, $entity, $this->field_name, $requested_language);
3290
    $this->assertEqual($display_language, $requested_language, 'Display language behave correctly when language fallback is disabled');
3291
  }
3292

    
3293
  /**
3294
   * Tests field translations when creating a new revision.
3295
   */
3296
  function testFieldFormTranslationRevisions() {
3297
    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
3298
    $this->drupalLogin($web_user);
3299

    
3300
    // Prepare the field translations.
3301
    field_test_entity_info_translatable($this->entity_type, TRUE);
3302
    $eid = 1;
3303
    $entity = field_test_create_stub_entity($eid, $eid, $this->instance['bundle']);
3304
    $available_languages = array_flip(field_available_languages($this->entity_type, $this->field));
3305
    unset($available_languages[LANGUAGE_NONE]);
3306
    $field_name = $this->field['field_name'];
3307

    
3308
    // Store the field translations.
3309
    $entity->is_new = TRUE;
3310
    foreach ($available_languages as $langcode => $value) {
3311
      $entity->{$field_name}[$langcode][0]['value'] = $value + 1;
3312
    }
3313
    field_test_entity_save($entity);
3314

    
3315
    // Create a new revision.
3316
    $langcode = field_valid_language(NULL);
3317
    $edit = array("{$field_name}[$langcode][0][value]" => $entity->{$field_name}[$langcode][0]['value'], 'revision' => TRUE);
3318
    $this->drupalPost('test-entity/manage/' . $eid . '/edit', $edit, t('Save'));
3319

    
3320
    // Check translation revisions.
3321
    $this->checkTranslationRevisions($eid, $eid, $available_languages);
3322
    $this->checkTranslationRevisions($eid, $eid + 1, $available_languages);
3323
  }
3324

    
3325
  /**
3326
   * Check if the field translation attached to the entity revision identified
3327
   * by the passed arguments were correctly stored.
3328
   */
3329
  private function checkTranslationRevisions($eid, $evid, $available_languages) {
3330
    $field_name = $this->field['field_name'];
3331
    $entity = field_test_entity_test_load($eid, $evid);
3332
    foreach ($available_languages as $langcode => $value) {
3333
      $passed = isset($entity->{$field_name}[$langcode]) && $entity->{$field_name}[$langcode][0]['value'] == $value + 1;
3334
      $this->assertTrue($passed, format_string('The @language translation for revision @revision was correctly stored', array('@language' => $langcode, '@revision' => $entity->ftvid)));
3335
    }
3336
  }
3337
}
3338

    
3339
/**
3340
 * Unit test class for field bulk delete and batch purge functionality.
3341
 */
3342
class FieldBulkDeleteTestCase extends FieldTestCase {
3343
  protected $field;
3344

    
3345
  public static function getInfo() {
3346
    return array(
3347
      'name' => 'Field bulk delete tests',
3348
      'description' => 'Bulk delete fields and instances, and clean up afterwards.',
3349
      'group' => 'Field API',
3350
    );
3351
  }
3352

    
3353
  /**
3354
   * Convenience function for Field API tests.
3355
   *
3356
   * Given an array of potentially fully-populated entities and an
3357
   * optional field name, generate an array of stub entities of the
3358
   * same fieldable type which contains the data for the field name
3359
   * (if given).
3360
   *
3361
   * @param $entity_type
3362
   *   The entity type of $entities.
3363
   * @param $entities
3364
   *   An array of entities of type $entity_type.
3365
   * @param $field_name
3366
   *   Optional; a field name whose data should be copied from
3367
   *   $entities into the returned stub entities.
3368
   * @return
3369
   *   An array of stub entities corresponding to $entities.
3370
   */
3371
  function _generateStubEntities($entity_type, $entities, $field_name = NULL) {
3372
    $stubs = array();
3373
    foreach ($entities as $id => $entity) {
3374
      $stub = entity_create_stub_entity($entity_type, entity_extract_ids($entity_type, $entity));
3375
      if (isset($field_name)) {
3376
        $stub->{$field_name} = $entity->{$field_name};
3377
      }
3378
      $stubs[$id] = $stub;
3379
    }
3380
    return $stubs;
3381
  }
3382

    
3383
  /**
3384
   * Tests that the expected hooks have been invoked on the expected entities.
3385
   *
3386
   * @param $expected_hooks
3387
   *   An array keyed by hook name, with one entry per expected invocation.
3388
   *   Each entry is the value of the "$entity" parameter the hook is expected
3389
   *   to have been passed.
3390
   * @param $actual_hooks
3391
   *   The array of actual hook invocations recorded by field_test_memorize().
3392
   */
3393
  function checkHooksInvocations($expected_hooks, $actual_hooks) {
3394
    foreach ($expected_hooks as $hook => $invocations) {
3395
      $actual_invocations = $actual_hooks[$hook];
3396

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

    
3400
      // Check that the hook was called for each expected argument.
3401
      foreach ($invocations as $argument) {
3402
        $found = FALSE;
3403
        foreach ($actual_invocations as $actual_arguments) {
3404
          if ($actual_arguments[1] == $argument) {
3405
            $found = TRUE;
3406
            break;
3407
          }
3408
        }
3409
        $this->assertTrue($found, "$hook() was called on expected argument");
3410
      }
3411
    }
3412
  }
3413

    
3414
  function setUp() {
3415
    parent::setUp('field_test');
3416

    
3417
    $this->fields = array();
3418
    $this->instances = array();
3419
    $this->entities = array();
3420
    $this->entities_by_bundles = array();
3421

    
3422
    // Create two bundles.
3423
    $this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
3424
    foreach ($this->bundles as $name => $desc) {
3425
      field_test_create_bundle($name, $desc);
3426
    }
3427

    
3428
    // Create two fields.
3429
    $field = array('field_name' => 'bf_1', 'type' => 'test_field', 'cardinality' => 1);
3430
    $this->fields[] = field_create_field($field);
3431
    $field = array('field_name' => 'bf_2', 'type' => 'test_field', 'cardinality' => 4);
3432
    $this->fields[] = field_create_field($field);
3433

    
3434
    // For each bundle, create an instance of each field, and 10
3435
    // entities with values for each field.
3436
    $id = 0;
3437
    $this->entity_type = 'test_entity';
3438
    foreach ($this->bundles as $bundle) {
3439
      foreach ($this->fields as $field) {
3440
        $instance = array(
3441
          'field_name' => $field['field_name'],
3442
          'entity_type' => $this->entity_type,
3443
          'bundle' => $bundle,
3444
          'widget' => array(
3445
            'type' => 'test_field_widget',
3446
          )
3447
        );
3448
        $this->instances[] = field_create_instance($instance);
3449
      }
3450

    
3451
      for ($i = 0; $i < 10; $i++) {
3452
        $entity = field_test_create_stub_entity($id, $id, $bundle);
3453
        foreach ($this->fields as $field) {
3454
          $entity->{$field['field_name']}[LANGUAGE_NONE] = $this->_generateTestFieldValues($field['cardinality']);
3455
        }
3456

    
3457
        $this->entities[$id] = $entity;
3458
        // Also keep track of the entities per bundle.
3459
        $this->entities_by_bundles[$bundle][$id] = $entity;
3460
        field_attach_insert($this->entity_type, $entity);
3461
        $id++;
3462
      }
3463
    }
3464
  }
3465

    
3466
  /**
3467
   * Verify that deleting an instance leaves the field data items in
3468
   * the database and that the appropriate Field API functions can
3469
   * operate on the deleted data and instance.
3470
   *
3471
   * This tests how EntityFieldQuery interacts with
3472
   * field_delete_instance() and could be moved to FieldCrudTestCase,
3473
   * but depends on this class's setUp().
3474
   */
3475
  function testDeleteFieldInstance() {
3476
    $bundle = reset($this->bundles);
3477
    $field = reset($this->fields);
3478

    
3479
    // There are 10 entities of this bundle.
3480
    $query = new EntityFieldQuery();
3481
    $found = $query
3482
      ->fieldCondition($field)
3483
      ->entityCondition('bundle', $bundle)
3484
      ->execute();
3485
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found before deleting');
3486

    
3487
    // Delete the instance.
3488
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3489
    field_delete_instance($instance);
3490

    
3491
    // The instance still exists, deleted.
3492
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
3493
    $this->assertEqual(count($instances), 1, 'There is one deleted instance');
3494
    $this->assertEqual($instances[0]['bundle'], $bundle, 'The deleted instance is for the correct bundle');
3495

    
3496
    // There are 0 entities of this bundle with non-deleted data.
3497
    $query = new EntityFieldQuery();
3498
    $found = $query
3499
      ->fieldCondition($field)
3500
      ->entityCondition('bundle', $bundle)
3501
      ->execute();
3502
    $this->assertTrue(!isset($found['test_entity']), 'No entities found after deleting');
3503

    
3504
    // There are 10 entities of this bundle when deleted fields are allowed, and
3505
    // their values are correct.
3506
    $query = new EntityFieldQuery();
3507
    $found = $query
3508
      ->fieldCondition($field)
3509
      ->entityCondition('bundle', $bundle)
3510
      ->deleted(TRUE)
3511
      ->execute();
3512
    field_attach_load($this->entity_type, $found[$this->entity_type], FIELD_LOAD_CURRENT, array('field_id' => $field['id'], 'deleted' => 1));
3513
    $this->assertEqual(count($found['test_entity']), 10, 'Correct number of entities found after deleting');
3514
    foreach ($found['test_entity'] as $id => $entity) {
3515
      $this->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity $id with deleted data loaded correctly");
3516
    }
3517
  }
3518

    
3519
  /**
3520
   * Verify that field data items and instances are purged when an
3521
   * instance is deleted.
3522
   */
3523
  function testPurgeInstance() {
3524
    // Start recording hook invocations.
3525
    field_test_memorize();
3526

    
3527
    $bundle = reset($this->bundles);
3528
    $field = reset($this->fields);
3529

    
3530
    // Delete the instance.
3531
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3532
    field_delete_instance($instance);
3533

    
3534
    // No field hooks were called.
3535
    $mem = field_test_memorize();
3536
    $this->assertEqual(count($mem), 0, 'No field hooks were called');
3537

    
3538
    $batch_size = 2;
3539
    for ($count = 8; $count >= 0; $count -= $batch_size) {
3540
      // Purge two entities.
3541
      field_purge_batch($batch_size);
3542

    
3543
      // There are $count deleted entities left.
3544
      $query = new EntityFieldQuery();
3545
      $found = $query
3546
        ->fieldCondition($field)
3547
        ->entityCondition('bundle', $bundle)
3548
        ->deleted(TRUE)
3549
        ->execute();
3550
      $this->assertEqual($count ? count($found['test_entity']) : count($found), $count, 'Correct number of entities found after purging 2');
3551
    }
3552

    
3553
    // Check hooks invocations.
3554
    // - hook_field_load() (multiple hook) should have been called on all
3555
    // entities by pairs of two.
3556
    // - hook_field_delete() should have been called once for each entity in the
3557
    // bundle.
3558
    $actual_hooks = field_test_memorize();
3559
    $hooks = array();
3560
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3561
    foreach (array_chunk($stubs, $batch_size, TRUE) as $chunk) {
3562
      $hooks['field_test_field_load'][] = $chunk;
3563
    }
3564
    foreach ($stubs as $stub) {
3565
      $hooks['field_test_field_delete'][] = $stub;
3566
    }
3567
    $this->checkHooksInvocations($hooks, $actual_hooks);
3568

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

    
3573
    // Purge the instance.
3574
    field_purge_batch($batch_size);
3575

    
3576
    // The instance is gone.
3577
    $instances = field_read_instances(array('field_id' => $field['id'], 'deleted' => 1), array('include_deleted' => 1, 'include_inactive' => 1));
3578
    $this->assertEqual(count($instances), 0, 'The instance is gone');
3579

    
3580
    // The field still exists, not deleted, because it has a second instance.
3581
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
3582
    $this->assertTrue(isset($fields[$field['id']]), 'The field exists and is not deleted');
3583
  }
3584

    
3585
  /**
3586
   * Verify that fields are preserved and purged correctly as multiple
3587
   * instances are deleted and purged.
3588
   */
3589
  function testPurgeField() {
3590
    // Start recording hook invocations.
3591
    field_test_memorize();
3592

    
3593
    $field = reset($this->fields);
3594

    
3595
    // Delete the first instance.
3596
    $bundle = reset($this->bundles);
3597
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3598
    field_delete_instance($instance);
3599

    
3600
    // Assert that hook_field_delete() was not called yet.
3601
    $mem = field_test_memorize();
3602
    $this->assertEqual(count($mem), 0, 'No field hooks were called.');
3603

    
3604
    // Purge the data.
3605
    field_purge_batch(10);
3606

    
3607
    // Check hooks invocations.
3608
    // - hook_field_load() (multiple hook) should have been called once, for all
3609
    // entities in the bundle.
3610
    // - hook_field_delete() should have been called once for each entity in the
3611
    // bundle.
3612
    $actual_hooks = field_test_memorize();
3613
    $hooks = array();
3614
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3615
    $hooks['field_test_field_load'][] = $stubs;
3616
    foreach ($stubs as $stub) {
3617
      $hooks['field_test_field_delete'][] = $stub;
3618
    }
3619
    $this->checkHooksInvocations($hooks, $actual_hooks);
3620

    
3621
    // Purge again to purge the instance.
3622
    field_purge_batch(0);
3623

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

    
3628
    // Delete the second instance.
3629
    $bundle = next($this->bundles);
3630
    $instance = field_info_instance($this->entity_type, $field['field_name'], $bundle);
3631
    field_delete_instance($instance);
3632

    
3633
    // Assert that hook_field_delete() was not called yet.
3634
    $mem = field_test_memorize();
3635
    $this->assertEqual(count($mem), 0, 'No field hooks were called.');
3636

    
3637
    // Purge the data.
3638
    field_purge_batch(10);
3639

    
3640
    // Check hooks invocations (same as above, for the 2nd bundle).
3641
    $actual_hooks = field_test_memorize();
3642
    $hooks = array();
3643
    $stubs = $this->_generateStubEntities($this->entity_type, $this->entities_by_bundles[$bundle], $field['field_name']);
3644
    $hooks['field_test_field_load'][] = $stubs;
3645
    foreach ($stubs as $stub) {
3646
      $hooks['field_test_field_delete'][] = $stub;
3647
    }
3648
    $this->checkHooksInvocations($hooks, $actual_hooks);
3649

    
3650
    // The field still exists, deleted.
3651
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1));
3652
    $this->assertTrue(isset($fields[$field['id']]) && $fields[$field['id']]['deleted'], 'The field exists and is deleted');
3653

    
3654
    // Purge again to purge the instance and the field.
3655
    field_purge_batch(0);
3656

    
3657
    // The field is gone.
3658
    $fields = field_read_fields(array('id' => $field['id']), array('include_deleted' => 1, 'include_inactive' => 1));
3659
    $this->assertEqual(count($fields), 0, 'The field is purged.');
3660
  }
3661
}
3662

    
3663
/**
3664
 * Tests entity properties.
3665
 */
3666
class EntityPropertiesTestCase extends FieldTestCase {
3667
  public static function getInfo() {
3668
    return array(
3669
      'name' => 'Entity properties',
3670
      'description' => 'Tests entity properties.',
3671
      'group' => 'Entity API',
3672
    );
3673
  }
3674

    
3675
  function setUp() {
3676
    parent::setUp('field_test');
3677
  }
3678

    
3679
  /**
3680
   * Tests label key and label callback of an entity.
3681
   */
3682
  function testEntityLabel() {
3683
    $entity_types = array(
3684
      'test_entity_no_label',
3685
      'test_entity_label',
3686
      'test_entity_label_callback',
3687
    );
3688

    
3689
    $entity = field_test_create_stub_entity();
3690

    
3691
    foreach ($entity_types as $entity_type) {
3692
      $label = entity_label($entity_type, $entity);
3693

    
3694
      switch ($entity_type) {
3695
        case 'test_entity_no_label':
3696
          $this->assertFalse($label, 'Entity with no label property or callback returned FALSE.');
3697
          break;
3698

    
3699
        case 'test_entity_label':
3700
          $this->assertEqual($label, $entity->ftlabel, 'Entity with label key returned correct label.');
3701
          break;
3702

    
3703
        case 'test_entity_label_callback':
3704
          $this->assertEqual($label, 'label callback ' . $entity->ftlabel, 'Entity with label callback returned correct label.');
3705
          break;
3706
      }
3707
    }
3708
  }
3709
}