1 field.test FieldBulkDeleteTestCase::testPurgeInstance()

Verify that field data items and instances are purged when an instance is deleted.

File

core/modules/field/tests/field.test, line 3386
Tests for field.module.

Class

FieldBulkDeleteTestCase
Unit test class for field bulk delete and batch purge functionality.

Code

function testPurgeInstance() {
  // Start recording hook invocations.
  field_test_memorize();

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

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

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

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

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

  // Check hooks invocations.
  // - hook_field_load() (multiple hook) should have been called on all
  // entities by pairs of two.
  // - hook_field_delete() should have been called once for each entity in the
  // bundle.
  $actual_hooks = field_test_memorize();
  $hooks = array();
  $entities = $this->convertToPartialEntities($this->entities_by_bundles[$bundle], $field['field_name']);
  foreach (array_chunk($entities, $batch_size, TRUE) as $chunk_entity) {
    $hooks['field_test_field_load'][] = $chunk_entity;
  }
  foreach ($entities as $entity) {
    $hooks['field_test_field_delete'][] = $entity;
  }
  $this->checkHooksInvocations($hooks, $actual_hooks);

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

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