field.test 74.8 KB
Newer Older
1
2
3
<?php
// $Id$

4
5
6
7
8
9
10
11
12
13
14
/**
 * @file
 * Unit test file for fields in core.
 */

/**
 * Unit test class for field_attach_* functions.
 *
 * All field_attach_* test work with all field_storage plugins and
 * all hook_field_attach_pre_{load,insert,update}() hooks.
 */
15
class FieldAttachTestCase extends DrupalWebTestCase {
16
  public static function getInfo() {
17
18
19
20
21
22
23
24
    return array(
      'name'  => t('Field attach tests'),
      'description'  => t("Test Field Attach API functions."),
      'group' => t('Field')
    );
  }

  function setUp() {
25
    parent::setUp('field_test');
26

27
    $this->field_name = drupal_strtolower($this->randomName() . '_field_name');
28
29
30
31
32
    $this->field = array('field_name' => $this->field_name, 'type' => 'test_field', 'cardinality' => 4);
    field_create_field($this->field);
    $this->instance = array(
      'field_name' => $this->field_name,
      'bundle' => 'test_bundle',
33
34
      'label' => $this->randomName() . '_label',
      'description' => $this->randomName() . '_description',
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
      'weight' => mt_rand(0, 127),
      'settings' => array(
        'test_instance_setting' => $this->randomName(),
      ),
      'widget' => array(
        'type' => 'test_field_widget',
        'label' => 'Test Field',
        'settings' => array(
          'test_widget_setting' => $this->randomName(),
        )
      )
    );
    field_create_instance($this->instance);
  }

50
  /**
51
   * Check field values insert, update and load.
52
   *
53
54
   * Works independently of the underlying field storage backend. Inserts or
   * updates random field data and then loads and verifies the data.
55
   */
56
  function testFieldAttachSaveLoad() {
57
58
59
60
61
    // Configure the instance so that we test hook_field_load() (see
    // field_test_field_load() in field_test.module).
    $this->instance['settings']['test_hook_field_load'] = TRUE;
    field_update_instance($this->instance);

62
63
64
    $entity_type = 'test_entity';
    $values = array();

65
    // TODO : test empty values filtering and "compression" (store consecutive deltas).
66
67

    // Preparation: create three revisions and store them in $revision array.
68
69
    for ($revision_id = 0; $revision_id < 3; $revision_id++) {
      $revision[$revision_id] = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
70
71
      // Note: we try to insert one extra value.
      $values[$revision_id] = $this->_generateTestFieldValues($this->field['cardinality'] + 1);
72
      $current_revision = $revision_id;
73
      // If this is the first revision do an insert.
74
75
76
      if (!$revision_id) {
        $revision[$revision_id]->{$this->field_name} = $values[$revision_id];
        field_attach_insert($entity_type, $revision[$revision_id]);
77
78
      }
      else {
79
        // Otherwise do an update.
80
81
        $revision[$revision_id]->{$this->field_name} = $values[$revision_id];
        field_attach_update($entity_type, $revision[$revision_id]);
82
83
      }
    }
84
85
86
87

    // Confirm current revision loads the correct data.
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
88
    // Number of values per field loaded equals the field cardinality.
89
    $this->assertEqual(count($entity->{$this->field_name}), $this->field['cardinality'], t('Currrent revision: expected number of values'));
90
91
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      // The field value loaded matches the one inserted or updated.
92
      $this->assertEqual($entity->{$this->field_name}[$delta]['value'] , $values[$current_revision][$delta]['value'], t('Currrent revision: expected value %delta was found.', array('%delta' => $delta)));
93
94
      // The value added in hook_field_load() is found.
      $this->assertEqual($entity->{$this->field_name}[$delta]['additional_key'], 'additional_value', t('Currrent revision: extra information for value %delta was found', array('%delta' => $delta)));
95
96
97
98
    }

    // Confirm each revision loads the correct data.
    foreach (array_keys($revision) as $revision_id) {
99
100
      $entity = field_test_create_stub_entity(0, $revision_id, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $entity));
101
      // Number of values per field loaded equals the field cardinality.
102
      $this->assertEqual(count($entity->{$this->field_name}), $this->field['cardinality'], t('Revision %revision_id: expected number of values.', array('%revision_id' => $revision_id)));
103
      for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
104
105
        // The field value loaded matches the one inserted or updated.
        $this->assertEqual($entity->{$this->field_name}[$delta]['value'], $values[$revision_id][$delta]['value'], t('Revision %revision_id: expected value %delta was found.', array('%revision_id' => $revision_id, '%delta' => $delta)));
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        // The value added in hook_field_load() is found.
        $this->assertEqual($entity->{$this->field_name}[$delta]['additional_key'], 'additional_value', t('Revision %revision_id: extra information for value %delta was found', array('%revision_id' => $revision_id, '%delta' => $delta)));
      }
    }
  }

  /**
   * Test the 'multiple' load feature.
   */
  function testFieldAttachLoadMultiple() {
    $entity_type = 'test_entity';

    // Define 2 bundles.
    $bundles = array(
      1 => 'test_bundle_1',
      2 => 'test_bundle_2',
    );
    field_test_create_bundle($bundles[1]);
    field_test_create_bundle($bundles[2]);
    // Define 3 fields:
    // - field_1 is in bundle_1 and bundle_2,
    // - field_2 is in bundle_1,
    // - field_3 is in bundle_2.
    $field_bundles_map = array(
      1 => array(1, 2),
      2 => array(1),
      3 => array(2),
    );
    for ($i = 1; $i <= 3; $i++) {
      $field_names[$i] = 'field_' . $i;
      $field = array('field_name' => $field_names[$i], 'type' => 'test_field');
      field_create_field($field);
      foreach ($field_bundles_map[$i] as $bundle) {
        $instance = array(
          'field_name' => $field_names[$i],
          'bundle' => $bundles[$bundle],
          'settings' => array(
            // Configure the instance so that we test hook_field_load()
            // (see field_test_field_load() in field_test.module).
            'test_hook_field_load' => TRUE,
          ),
        );
        field_create_instance($instance);
      }
    }

    // Create one test entity per bundle, with random values.
    foreach ($bundles as $index => $bundle) {
      $entities[$index] = field_test_create_stub_entity($index, $index, $bundle);
      $entity = clone($entities[$index]);
      $instances = field_info_instances($bundle);
      foreach ($instances as $field_name => $instance) {
        $values[$index][$field_name] = mt_rand(1, 127);
        $entity->$field_name = array(array('value' => $values[$index][$field_name]));
      }
      field_attach_insert($entity_type, $entity);
    }

    // Check that a single load correctly loads field values for both entities.
    field_attach_load($entity_type, $entities);
    foreach ($entities as $index => $entity) {
      $instances = field_info_instances($bundles[$index]);
      foreach ($instances as $field_name => $instance) {
        // The field value loaded matches the one inserted.
        $this->assertEqual($entity->{$field_name}[0]['value'], $values[$index][$field_name], t('Entity %index: expected value was found.', array('%index' => $index)));
        // The value added in hook_field_load() is found.
        $this->assertEqual($entity->{$field_name}[0]['additional_key'], 'additional_value', t('Entity %index: extra information was found', array('%index' => $index)));
173
174
175
      }
    }
  }
176

177
178
179
  /**
   * Tests insert and update with missing or NULL fields.
   */
180
181
  function testFieldAttachSaveMissingData() {
    $entity_type = 'test_entity';
182
    $entity_init = field_test_create_stub_entity();
183

184
    // Insert: Field is missing.
185
    $entity = clone($entity_init);
186
    field_attach_insert($entity_type, $entity);
187
188
189
190

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: missing field results in no value saved'));
191

192
    // Insert: Field is NULL.
193
194
    field_cache_clear();
    $entity = clone($entity_init);
195
196
197
    $entity->{$this->field_name} = NULL;
    field_attach_insert($entity_type, $entity);

198
199
200
201
202
203
204
    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: NULL field results in no value saved'));

    // Add some real data.
    field_cache_clear();
    $entity = clone($entity_init);
205
    $values = $this->_generateTestFieldValues(1);
206
    $entity->{$this->field_name} = $values;
207
    field_attach_insert($entity_type, $entity);
208
209
210
211

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertEqual($entity->{$this->field_name}, $values, t('Field data saved'));
212

213
    // Update: Field is missing. Data should survive.
214
215
    field_cache_clear();
    $entity = clone($entity_init);
216
    field_attach_update($entity_type, $entity);
217
218
219
220

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertEqual($entity->{$this->field_name}, $values, t('Update: missing field leaves existing values in place'));
221

222
    // Update: Field is NULL. Data should be wiped.
223
224
    field_cache_clear();
    $entity = clone($entity_init);
225
226
    $entity->{$this->field_name} = NULL;
    field_attach_update($entity_type, $entity);
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Update: NULL field removes existing values'));
  }

  /**
   * Test insert with missing or NULL fields, with default value.
   */
  function testFieldAttachSaveMissingDataDefaultValue() {
    // Add a default value.
    $this->instance['default_value_function'] = 'field_test_default_value';
    field_update_instance($this->instance);

    $entity_type = 'test_entity';
    $entity_init = field_test_create_stub_entity();

    // Insert: Field is NULL.
    $entity = clone($entity_init);
    $entity->{$this->field_name} = NULL;
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $this->assertTrue(empty($entity->{$this->field_name}), t('Insert: NULL field results in no value saved'));

    // Insert: Field is missing.
    field_cache_clear();
    $entity = clone($entity_init);
    field_attach_insert($entity_type, $entity);

    $entity = clone($entity_init);
    field_attach_load($entity_type, array($entity->ftid => $entity));
    $values = field_test_default_value($entity_type, $entity, $this->field, $this->instance);
    $this->assertEqual($entity->{$this->field_name}, $values, t('Insert: missing field results in default value saved'));
262
263
  }

264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
  /**
   * Test field_attach_query().
   */
  function testFieldAttachQuery() {
    $cardinality = $this->field['cardinality'];

    // Create an additional bundle with an instance of the field.
    field_test_create_bundle('test_bundle_1', 'Test Bundle 1');
    $this->instance2 = $this->instance;
    $this->instance2['bundle'] = 'test_bundle_1';
    field_create_instance($this->instance2);

    // Create two test objects, using two different types and bundles.
    $entity_types = array(1 => 'test_entity', 2 => 'test_cacheable_entity');
    $entities = array(1 => field_test_create_stub_entity(1, 1, 'test_bundle'), 2 => field_test_create_stub_entity(2, 2, 'test_bundle_1'));

    // Create first test object with random (distinct) values.
    $values = array();
    for ($delta = 0; $delta < $cardinality; $delta++) {
      do {
        $value = mt_rand(1, 127);
      } while (in_array($value, $values));
      $values[$delta] = $value;
      $entities[1]->{$this->field_name}[$delta] = array('value' => $values[$delta]);
    }
    field_attach_insert($entity_types[1], $entities[1]);

    // Create second test object, sharing a value with the first one.
    $common_value = $values[$cardinality - 1];
    $entities[2]->{$this->field_name} = array(array('value' => $common_value));
    field_attach_insert($entity_types[2], $entities[2]);

    // Query on the object's values.
    for ($delta = 0; $delta < $cardinality; $delta++) {
      $conditions = array(array('value', $values[$delta]));
      $result = field_attach_query($this->field_name, $conditions);
      $this->assertTrue(isset($result[$entity_types[1]][1]), t('Query on value %delta returns the object', array('%delta' => $delta)));
    }

    // Query on a value that is not in the object.
    do {
      $different_value = mt_rand(1, 127);
    } while (in_array($different_value, $values));
    $conditions = array(array('value', $different_value));
    $result = field_attach_query($this->field_name, $conditions);
    $this->assertFalse(isset($result[$entity_types[1]][1]), t("Query on a value that is not in the object doesn't return the object"));

    // Query on the value shared by both objects, and discriminate using
    // additional conditions.

    $conditions = array(array('value', $common_value));
    $result = field_attach_query($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_types[1]][1]) && isset($result[$entity_types[2]][2]), t('Query on a value common to both objects returns both objects'));

    $conditions = array(array('type', $entity_types[1]), array('value', $common_value));
    $result = field_attach_query($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_types[1]][1]) && !isset($result[$entity_types[2]][2]), t("Query on a value common to both objects and a 'type' condition only returns the relevant object"));

    $conditions = array(array('bundle', $entities[1]->fttype), array('value', $common_value));
    $result = field_attach_query($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_types[1]][1]) && !isset($result[$entity_types[2]][2]), t("Query on a value common to both objects and a 'bundle' condition only returns the relevant object"));

    $conditions = array(array('entity_id', $entities[1]->ftid), array('value', $common_value));
    $result = field_attach_query($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_types[1]][1]) && !isset($result[$entity_types[2]][2]), t("Query on a value common to both objects and an 'entity_id' condition only returns the relevant object"));

    // Test FIELD_QUERY_RETURN_IDS result format.
    $conditions = array(array('value', $values[0]));
    $result = field_attach_query($this->field_name, $conditions);
    $expected = array(
      $entity_types[1] => array(
        $entities[1]->ftid => $entities[1]->ftid,
      )
    );
    $this->assertEqual($result, $expected, t('FIELD_QUERY_RETURN_IDS result format returns the expect result'));

    // Test FIELD_QUERY_RETURN_VALUES result format.
    // Configure the instances so that we test hook_field_load() (see
    // field_test_field_load() in field_test.module).
    $this->instance['settings']['test_hook_field_load'] = TRUE;
    field_update_instance($this->instance);
    $this->instance2['settings']['test_hook_field_load'] = TRUE;
    field_update_instance($this->instance2);

    // Query for one of the values in the 1st object and the value shared by
    // both objects.
    $conditions = array(array('value', array($values[0], $common_value)));
    $result = field_attach_query($this->field_name, $conditions, FIELD_QUERY_RETURN_VALUES);
    $expected = array(
      $entity_types[1] => array(
        $entities[1]->ftid => (object) array(
          'ftid' => $entities[1]->ftid,
          'ftvid' => $entities[1]->ftvid,
          'fttype' => $entities[1]->fttype,
          $this->field_name => array(
            array('value' => $values[0], 'additional_key' => 'additional_value'),
            array('value' => $common_value, 'additional_key' => 'additional_value'),
          ),
        ),
      ),
      $entity_types[2] => array(
        $entities[2]->ftid => (object) array(
          'ftid' => $entities[2]->ftid,
          'ftvid' => $entities[2]->ftvid,
          'fttype' => $entities[2]->fttype,
          $this->field_name => array(
            array('value' => $common_value, 'additional_key' => 'additional_value'),
          ),
        ),
      ),
    );
    $this->assertEqual($result, $expected, t('FIELD_QUERY_RETURN_VALUES result format returns the expect result'));
  }

  /**
   * Test field_attach_query_revisions().
   */
  function testFieldAttachQueryRevisions() {
    $cardinality = $this->field['cardinality'];

    // Create first object revision with random (distinct) values.
    $entity_type = 'test_entity';
    $entities = array(1 => field_test_create_stub_entity(1, 1), 2 => field_test_create_stub_entity(1, 2));
    $values = array();
    for ($delta = 0; $delta < $cardinality; $delta++) {
      do {
        $value = mt_rand(1, 127);
      } while (in_array($value, $values));
      $values[$delta] = $value;
      $entities[1]->{$this->field_name}[$delta] = array('value' => $values[$delta]);
    }
    field_attach_insert($entity_type, $entities[1]);

    // Create second object revision, sharing a value with the first one.
    $common_value = $values[$cardinality - 1];
    $entities[2]->{$this->field_name}[0] = array('value' => $common_value);
    field_attach_update($entity_type, $entities[2]);

    // Query on the object's values.
    for ($delta = 0; $delta < $cardinality; $delta++) {
      $conditions = array(array('value', $values[$delta]));
      $result = field_attach_query_revisions($this->field_name, $conditions);
      $this->assertTrue(isset($result[$entity_type][1]), t('Query on value %delta returns the object', array('%delta' => $delta)));
    }

    // Query on a value that is not in the object.
    do {
      $different_value = mt_rand(1, 127);
    } while (in_array($different_value, $values));
    $conditions = array(array('value', $different_value));
    $result = field_attach_query_revisions($this->field_name, $conditions);
    $this->assertFalse(isset($result[$entity_type][1]), t("Query on a value that is not in the object doesn't return the object"));

    // Query on the value shared by both objects, and discriminate using
    // additional conditions.

    $conditions = array(array('value', $common_value));
    $result = field_attach_query_revisions($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_type][1]) && isset($result[$entity_type][2]), t('Query on a value common to both objects returns both objects'));

    $conditions = array(array('revision_id', $entities[1]->ftvid), array('value', $common_value));
    $result = field_attach_query_revisions($this->field_name, $conditions);
    $this->assertTrue(isset($result[$entity_type][1]) && !isset($result[$entity_type][2]), t("Query on a value common to both objects and a 'revision_id' condition only returns the relevant object"));

    // Test FIELD_QUERY_RETURN_IDS result format.
    $conditions = array(array('value', $values[0]));
    $result = field_attach_query_revisions($this->field_name, $conditions);
    $expected = array(
      $entity_type => array(
        $entities[1]->ftvid => $entities[1]->ftid,
      )
    );
    $this->assertEqual($result, $expected, t('FIELD_QUERY_RETURN_IDS result format returns the expect result'));

    // Test FIELD_QUERY_RETURN_VALUES result format.
    // Configure the instance so that we test hook_field_load() (see
    // field_test_field_load() in field_test.module).
    $this->instance['settings']['test_hook_field_load'] = TRUE;
    field_update_instance($this->instance);

    // Query for one of the values in the 1st object and the value shared by
    // both objects.
    $conditions = array(array('value', array($values[0], $common_value)));
    $result = field_attach_query_revisions($this->field_name, $conditions, FIELD_QUERY_RETURN_VALUES);
    $expected = array(
      $entity_type => array(
        $entities[1]->ftvid => (object) array(
          'ftid' => $entities[1]->ftid,
          'ftvid' => $entities[1]->ftvid,
          'fttype' => $entities[1]->fttype,
          $this->field_name => array(
            array('value' => $values[0], 'additional_key' => 'additional_value'),
            array('value' => $common_value, 'additional_key' => 'additional_value'),
          ),
        ),
        $entities[2]->ftvid => (object) array(
          'ftid' => $entities[2]->ftid,
          'ftvid' => $entities[2]->ftvid,
          'fttype' => $entities[2]->fttype,
          $this->field_name => array(
            array('value' => $common_value, 'additional_key' => 'additional_value'),
          ),
        ),
      ),
    );
    $this->assertEqual($result, $expected, t('FIELD_QUERY_RETURN_VALUES result format returns the expect result'));
  }

472
473
474
475
476
  function testFieldAttachViewAndPreprocess() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Populate values to be displayed.
477
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    $entity->{$this->field_name} = $values;

    // Simple formatter, label displayed.
    $formatter_setting = $this->randomName();
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'field_test_default',
        'settings' => array(
          'test_formatter_setting' => $formatter_setting,
        )
      ),
    );
    field_update_instance($this->instance);
    $entity->content = field_attach_view($entity_type, $entity);
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertRaw($this->instance['label'], "Label is displayed.");
    foreach ($values as $delta => $value) {
      $this->content = $output;
      $this->assertRaw("$formatter_setting|{$value['value']}", "Value $delta is displayed, formatter settings are applied.");
    }

    // Label hidden.
    $this->instance['display']['full']['label'] = 'hidden';
    field_update_instance($this->instance);
    $entity->content = field_attach_view($entity_type, $entity);
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertNoRaw($this->instance['label'], "Hidden label: label is not displayed.");

    // Field hidden.
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'hidden',
      ),
    );
    field_update_instance($this->instance);
    $entity->content = field_attach_view($entity_type, $entity);
    $output = drupal_render($entity->content);
    $this->content = $output;
    $this->assertNoRaw($this->instance['label'], "Hidden field: label is not displayed.");
    foreach ($values as $delta => $value) {
      $this->assertNoRaw($value['value'], "Hidden field: value $delta is not displayed.");
    }

    // Multiple formatter.
    $formatter_setting = $this->randomName();
    $this->instance['display'] = array(
      'full' => array(
        'label' => 'above',
        'type' => 'field_test_multiple',
        'settings' => array(
          'test_formatter_setting_multiple' => $formatter_setting,
        )
      ),
    );
    field_update_instance($this->instance);
    $entity->content = field_attach_view($entity_type, $entity);
    $output = drupal_render($entity->content);
    $display = $formatter_setting;
    foreach ($values as $delta => $value) {
      $display .= "|$delta:{$value['value']}";
    }
    $this->content = $output;
    $this->assertRaw($display, "Multiple formatter: all values are displayed, formatter settings are applied.");

    // TODO:
    // - check display order with several fields
  }

  function testFieldAttachDelete() {
    $entity_type = 'test_entity';
    $rev[0] = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Create revision 0
555
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
    $rev[0]->{$this->field_name} = $values;
    field_attach_insert($entity_type, $rev[0]);

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

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

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

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

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

    // Delete all field data, confirm nothing loads
    field_attach_delete($entity_type, $rev[2]);
    foreach (array(0, 1, 2) as $vid) {
      $read = field_test_create_stub_entity(0, $vid, $this->instance['bundle']);
      field_attach_load_revision($entity_type, array(0 => $read));
      $this->assertIdentical($read->{$this->field_name}, array(), "The test object revision $vid is deleted.");
    }
    $read = field_test_create_stub_entity(0, 2, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $read));
598
    $this->assertIdentical($read->{$this->field_name}, array(), t('The test object current revision is deleted.'));
599
600
601
602
603
  }

  function testFieldAttachCreateRenameBundle() {
    // Create a new bundle. This has to be initiated by the module so that its
    // hook_fieldable_info() is consistent.
604
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
605
    field_test_create_bundle($new_bundle);
606
607
608
609
610
611
612

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

    // Save an object with data in the field.
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
613
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
614
615
616
617
618
619
620
621
622
623
624
    $entity->{$this->field_name} = $values;
    $entity_type = 'test_entity';
    field_attach_insert($entity_type, $entity);

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

    // Rename the bundle. This has to be initiated by the module so that its
    // hook_fieldable_info() is consistent.
625
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
    field_test_rename_bundle($this->instance['bundle'], $new_bundle);

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

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

  function testFieldAttachDeleteBundle() {
    // Create a new bundle. This has to be initiated by the module so that its
    // hook_fieldable_info() is consistent.
641
    $new_bundle = 'test_bundle_' . drupal_strtolower($this->randomName());
642
    field_test_create_bundle($new_bundle);
643
644
645
646
647
648

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

    // Create a second field for the test bundle
649
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
650
651
652
653
654
    $field = array('field_name' => $field_name, 'type' => 'test_field', 'cardinality' => 1);
    field_create_field($field);
    $instance = array(
      'field_name' => $field_name,
      'bundle' => $this->instance['bundle'],
655
656
      'label' => $this->randomName() . '_label',
      'description' => $this->randomName() . '_description',
657
658
659
660
661
662
663
664
665
666
      'weight' => mt_rand(0, 127),
      // test_field has no instance settings
      'widget' => array(
        'type' => 'test_field_widget',
        'settings' => array(
          'size' => mt_rand(0, 255))));
    field_create_instance($instance);

    // Save an object with data for both fields
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
667
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
668
    $entity->{$this->field_name} = $values;
669
    $entity->{$field_name} = $this->_generateTestFieldValues(1);
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
    $entity_type = 'test_entity';
    field_attach_insert($entity_type, $entity);

    // Verify the fields are present on load
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
    $this->assertEqual(count($entity->{$this->field_name}), 4, "First field got loaded");
    $this->assertEqual(count($entity->{$field_name}), 1, "Second field got loaded");

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

    // Verify no data gets loaded
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);
    field_attach_load($entity_type, array(0 => $entity));
    $this->assertFalse(isset($entity->{$this->field_name}), "No data for first field");
    $this->assertFalse(isset($entity->{$field_name}), "No data for second field");

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

694
695
696
  /**
   * Test field cache.
   */
697
  function testFieldAttachCache() {
698
    // Initialize random values and a test entity.
699
    $entity_init = field_test_create_stub_entity(1, 1, $this->instance['bundle']);
700
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
701
702
703
704

    $noncached_type = 'test_entity';
    $cached_type = 'test_cacheable_entity';

705

706
    // Non-cacheable entity type.
707
    $cid = "field:$noncached_type:{$entity_init->ftid}";
708

709
710
    // Check that no initial cache entry is present.
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no initial cache entry'));
711

712
    // Save, and check that no cache entry is present.
713
    $entity = clone($entity_init);
714
    $entity->{$this->field_name} = $values;
715
    field_attach_insert($noncached_type, $entity);
716
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on insert'));
717

718
    // Load, and check that no cache entry is present.
719
    $entity = clone($entity_init);
720
721
    field_attach_load($noncached_type, array($entity->ftid => $entity));
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Non-cached: no cache entry on load'));
722

723

724
    // Cacheable entity type.
725
    $cid = "field:$cached_type:{$entity_init->ftid}";
726

727
728
    // Check that no initial cache entry is present.
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no initial cache entry'));
729

730
    // Save, and check that no cache entry is present.
731
    $entity = clone($entity_init);
732
    $entity->{$this->field_name} = $values;
733
    field_attach_insert($cached_type, $entity);
734
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on insert'));
735

736
    // Load, and check that a cache entry is present with the expected values.
737
    $entity = clone($entity_init);
738
    field_attach_load($cached_type, array($entity->ftid => $entity));
739
    $cache = cache_get($cid, 'cache_field');
740
    $this->assertEqual($cache->data[$this->field_name], $values, t('Cached: correct cache entry on load'));
741

742
743
    // Update with different values, and check that the cache entry is wiped.
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
744
    $entity = clone($entity_init);
745
746
747
748
749
    $entity->{$this->field_name} = $values;
    field_attach_update($cached_type, $entity);
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on update'));

    // Load, and check that a cache entry is present with the expected values.
750
    $entity = clone($entity_init);
751
752
753
754
755
    field_attach_load($cached_type, array($entity->ftid => $entity));
    $cache = cache_get($cid, 'cache_field');
    $this->assertEqual($cache->data[$this->field_name], $values, t('Cached: correct cache entry on load'));

    // Create a new revision, and check that the cache entry is wiped.
756
    $entity_init = field_test_create_stub_entity(1, 2, $this->instance['bundle']);
757
    $values = $this->_generateTestFieldValues($this->field['cardinality']);
758
    $entity = clone($entity_init);
759
760
761
762
763
764
    $entity->{$this->field_name} = $values;
    field_attach_update($cached_type, $entity);
    $cache = cache_get($cid, 'cache_field');
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry on new revision creation'));

    // Load, and check that a cache entry is present with the expected values.
765
    $entity = clone($entity_init);
766
767
768
769
770
    field_attach_load($cached_type, array($entity->ftid => $entity));
    $cache = cache_get($cid, 'cache_field');
    $this->assertEqual($cache->data[$this->field_name], $values, t('Cached: correct cache entry on load'));

    // Delete, and check that the cache entry is wiped.
771
    field_attach_delete($cached_type, $entity);
772
    $this->assertFalse(cache_get($cid, 'cache_field'), t('Cached: no cache entry after delete'));
773
774
775
  }

  // Verify that field_attach_validate() invokes the correct
776
  // hook_field_validate.
777
778
779
780
781
782
783
784
785
786
787
788
789
790
  function testFieldAttachValidate() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Set up values to generate errors
    $values = array();
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      $values[$delta]['value'] = -1;
      $values[$delta]['_error_element'] = 'field_error_' . $delta;
    }
    // Arrange for item 1 not to generate an error
    $values[1]['value'] = 1;
    $entity->{$this->field_name} = $values;

791
792
793
794
795
796
    try {
      field_attach_validate($entity_type, $entity);
    }
    catch (FieldValidationException $e) {
      $errors = $e->errors;
    }
797
798
799

    foreach ($values as $delta => $value) {
      if ($value['value'] != 1) {
800
801
802
        $this->assertIdentical($errors[$this->field_name][$delta][0]['error'], 'field_test_invalid', "Error set on value $delta");
        $this->assertEqual(count($errors[$this->field_name][$delta]), 1, "Only one error set on value $delta");
        unset($errors[$this->field_name][$delta]);
803
804
      }
      else {
805
        $this->assertFalse(isset($errors[$this->field_name][$delta]), "No error set on value $delta");
806
807
      }
    }
808
    $this->assertEqual(count($errors[$this->field_name]), 0, 'No extraneous errors set');
809
810
  }

811
  // Validate that FAPI elements are generated. This could be much
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
  // more thorough, but it does verify that the correct widgets show up.
  function testFieldAttachForm() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    $form = $form_state = array();
    field_attach_form($entity_type, $entity, $form, $form_state);

    $this->assertEqual($form[$this->field_name]['#title'], $this->instance['label'], "Form title is {$this->instance['label']}");
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      // field_test_widget uses 'textfield'
      $this->assertEqual($form[$this->field_name][$delta]['value']['#type'], 'textfield', "Form delta $delta widget is textfield");
    }
  }

  function testFieldAttachSubmit() {
    $entity_type = 'test_entity';
    $entity = field_test_create_stub_entity(0, 0, $this->instance['bundle']);

    // Build the form.
    $form = $form_state = array();
    field_attach_form($entity_type, $entity, $form, $form_state);

    // Simulate incoming values.
    $values = array();
    $weights = array();
    for ($delta = 0; $delta < $this->field['cardinality']; $delta++) {
      $values[$delta]['value'] = mt_rand(1, 127);
      // Assign random weight.
      do {
        $weight = mt_rand(0, $this->field['cardinality']);
      } while (in_array($weight, $weights));
      $weights[$delta] = $weight;
      $values[$delta]['_weight'] = $weight;
    }
    // Leave an empty value. 'field_test' fields are empty if empty().
    $values[1]['value'] = 0;

    $form_state['values'] = array($this->field_name => $values);
    field_attach_submit($entity_type, $entity, $form, $form_state);

    asort($weights);
    $expected_values = array();
    foreach ($weights as $key => $value) {
      if ($key != 1) {
        $expected_values[] = array('value' => $values[$key]['value']);
      }
    }
    $this->assertIdentical($entity->{$this->field_name}, $expected_values, 'Submit filters empty values');
  }
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

  /**
   * Generate random values for a field_test field.
   *
   * @param $cardinality
   *   Number of values to generate.
   * @return
   *  An array of random values, in the format expected for field values.
   */
  function _generateTestFieldValues($cardinality) {
    $values = array();
    for ($i = 0; $i < $cardinality; $i++) {
      // field_test fields treat 0 as 'empty value'.
      $values[$i]['value'] = mt_rand(1, 127);
    }
    return $values;
  }
879
880
881
882
}

class FieldInfoTestCase extends DrupalWebTestCase {

883
  public static function getInfo() {
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
    return array(
      'name'  => t('Field info tests'),
      'description'  => t("Get information about existing fields, instances and bundles."),
      'group' => t('Field')
    );
  }

  function setUp() {
    parent::setUp('field_sql_storage', 'field', 'field_test');
  }

  function testFieldInfo() {
    // Test that field_test module's fields, widgets, and formatters show up.
    $field_test_info = field_test_field_info();
    $formatter_info = field_test_field_formatter_info();
    $widget_info = field_test_field_widget_info();

    $info = field_info_field_types();
    foreach ($field_test_info as $t_key => $field_type) {
      foreach ($field_type as $key => $val) {
        $this->assertEqual($info[$t_key][$key], $val, t("Field type $t_key key $key is $val"));
      }
      $this->assertEqual($info[$t_key]['module'], 'field_test',  t("Field type field_test module appears"));
    }

    $info = field_info_formatter_types();
    foreach ($formatter_info as $f_key => $formatter) {
      foreach ($formatter as $key => $val) {
        $this->assertEqual($info[$f_key][$key], $val, t("Formatter type $f_key key $key is $val"));
      }
      $this->assertEqual($info[$f_key]['module'], 'field_test',  t("Formatter type field_test module appears"));
    }

    $info = field_info_widget_types();
    foreach ($widget_info as $w_key => $widget) {
      foreach ($widget as $key => $val) {
        $this->assertEqual($info[$w_key][$key], $val, t("Widget type $w_key key $key is $val"));
      }
      $this->assertEqual($info[$w_key]['module'], 'field_test',  t("Widget type field_test module appears"));
    }

925
926
    // Verify that no unexpected instances exist.
    $core_fields = field_info_fields();
927
928
929
930
931
    $instances = field_info_instances(FIELD_TEST_BUNDLE);
    $this->assertTrue(empty($instances), t('With no instances, info bundles is empty.'));

    // Create a field, verify it shows up.
    $field = array(
932
      'field_name' => drupal_strtolower($this->randomName()),
933
934
935
936
      'type' => 'test_field',
    );
    field_create_field($field);
    $fields = field_info_fields();
937
    $this->assertEqual(count($fields), count($core_fields) + 1, t('One new field exists'));
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
    $this->assertEqual($fields[$field['field_name']]['field_name'], $field['field_name'], t('info fields contains field name'));
    $this->assertEqual($fields[$field['field_name']]['type'], $field['type'], t('info fields contains field type'));
    $this->assertEqual($fields[$field['field_name']]['module'], 'field_test', t('info fields contains field module'));
    $settings = array('test_field_setting' => 'dummy test string');
    foreach ($settings as $key => $val) {
      $this->assertEqual($fields[$field['field_name']]['settings'][$key], $val, t("Field setting $key has correct default value $val"));
    }
    $this->assertEqual($fields[$field['field_name']]['cardinality'], 1, t('info fields contains cardinality 1'));
    $this->assertEqual($fields[$field['field_name']]['active'], 1, t('info fields contains active 1'));

    // Create an instance, verify that it shows up
    $instance = array(
      'field_name' => $field['field_name'],
      'bundle' => FIELD_TEST_BUNDLE,
      'label' => $this->randomName(),
      'description' => $this->randomName(),
      'weight' => mt_rand(0, 127),
      // test_field has no instance settings
      'widget' => array(
        'type' => 'test_field_widget',
        'settings' => array(
          'test_setting' => 999)));
    field_create_instance($instance);

    $instances = field_info_instances($instance['bundle']);
    $this->assertEqual(count($instances), 1, t('One instance shows up in info when attached to a bundle.'));
    $this->assertTrue($instance < $instances[$instance['field_name']], t('Instance appears in info correctly'));
  }

  // Test that the field_info settings convenience functions work
  function testSettingsInfo() {
    $info = field_test_field_info();
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_field_settings($type), $data['settings'], "field_info_field_settings returns {$type}'s field settings");
      $this->assertIdentical(field_info_instance_settings($type), $data['instance_settings'], "field_info_field_settings returns {$type}'s field instance settings");
    }

    $info = field_test_field_widget_info();
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_widget_settings($type), $data['settings'], "field_info_widget_settings returns {$type}'s widget settings");
    }

    $info = field_test_field_formatter_info();
    foreach ($info as $type => $data) {
      $this->assertIdentical(field_info_formatter_settings($type), $data['settings'], "field_info_formatter_settings returns {$type}'s formatter settings");
    }
  }
}

class FieldFormTestCase extends DrupalWebTestCase {
988
  public static function getInfo() {
989
990
991
992
993
994
995
996
997
998
999
1000
    return array(
      'name'  => t('Field form tests'),
      'description'  => t("Test Field form handling."),
      'group' => t('Field')
    );
  }

  function setUp() {
    parent::setUp('field_sql_storage', 'field', 'field_test');

    $web_user = $this->drupalCreateUser(array('access field_test content', 'administer field_test content'));
    $this->drupalLogin($web_user);
For faster browsing, not all history is shown. View entire blame