function BulkDeleteTest::testDeleteFieldInstance

Verify that deleting an instance leaves the field data items in the database and that the appropriate Field API functions can operate on the deleted data and instance.

This tests how EntityFieldQuery interacts with field_delete_instance() and could be moved to FieldCrudTestCase, but depends on this class's setUp().

File

drupal/core/modules/field/lib/Drupal/field/Tests/BulkDeleteTest.php, line 156
Definition of Drupal\field\Tests\BulkDeleteTest.

Class

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

Namespace

Drupal\field\Tests

Code

function testDeleteFieldInstance() {
  $bundle = reset($this->bundles);
  $field = reset($this->fields);
  $field_name = $field['field_name'];
  $factory = drupal_container()
    ->get('entity.query');

  // There are 10 entities of this bundle.
  $found = $factory
    ->get('test_entity')
    ->condition('fttype', $bundle)
    ->execute();
  $this
    ->assertEqual(count($found), 10, 'Correct number of entities found before deleting');

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

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

  // There are 0 entities of this bundle with non-deleted data.
  $found = $factory
    ->get('test_entity')
    ->condition('fttype', $bundle)
    ->condition("{$field_name}.deleted", 0)
    ->execute();
  $this
    ->assertFalse($found, 'No entities found after deleting');

  // There are 10 entities of this bundle when deleted fields are allowed, and
  // their values are correct.
  $found = $factory
    ->get('test_entity')
    ->condition('fttype', $bundle)
    ->condition("{$field_name}.deleted", 1)
    ->sort('ftid')
    ->execute();
  $ids = (object) array(
    'entity_type' => 'test_entity',
    'bundle' => $bundle,
  );
  $entities = array();
  foreach ($found as $entity_id) {
    $ids->entity_id = $entity_id;
    $entities[$entity_id] = _field_create_entity_from_ids($ids);
  }
  field_attach_load($this->entity_type, $entities, FIELD_LOAD_CURRENT, array(
    'field_id' => $field['id'],
    'deleted' => 1,
  ));
  $this
    ->assertEqual(count($found), 10, 'Correct number of entities found after deleting');
  foreach ($entities as $id => $entity) {
    $this
      ->assertEqual($this->entities[$id]->{$field['field_name']}, $entity->{$field['field_name']}, "Entity {$id} with deleted data loaded correctly");
  }
}