You are here

public function EntityMetadataIntegrationTestCase::testFileFields in Entity API 7

Test making use of a file field.

File

./entity.test, line 1986
Entity CRUD API tests.

Class

EntityMetadataIntegrationTestCase
Tests provided entity property info of the core modules.

Code

public function testFileFields() {
  $file = $this
    ->createFile();

  // Create a file field.
  $field = array(
    'field_name' => 'field_file',
    'type' => 'file',
    'cardinality' => 2,
    'settings' => array(
      'display_field' => TRUE,
    ),
  );
  field_create_field($field);
  $instance = array(
    'field_name' => 'field_file',
    'entity_type' => 'node',
    'label' => 'File',
    'bundle' => 'article',
    'settings' => array(
      'description_field' => TRUE,
    ),
    'required' => FALSE,
    'widget' => array(
      'type' => 'file_generic',
      'weight' => -1,
    ),
  );
  field_create_instance($instance);
  $node = $this
    ->drupalCreateNode(array(
    'type' => 'article',
  ));
  $wrapper = entity_metadata_wrapper('node', $node);
  $wrapper->field_file[0] = array(
    'fid' => $file->fid,
    'display' => FALSE,
  );
  $this
    ->assertEqual($file->filename, $wrapper->field_file[0]->file->name
    ->value(), 'File has been specified.');
  $wrapper->field_file[0]->description = 'foo';
  $wrapper->field_file[0]->display = TRUE;
  $this
    ->assertEqual($wrapper->field_file[0]->description
    ->value(), 'foo', 'File description has been correctly set.');

  // Try saving the node and make sure the information is still there after
  // loading the node again, thus the correct data structure has been written.
  node_save($node);
  $node = node_load($node->nid, NULL, TRUE);
  $wrapper = entity_metadata_wrapper('node', $node);
  $this
    ->assertEqual($wrapper->field_file[0]->description
    ->value(), 'foo', 'File description has been correctly set.');
  $this
    ->assertEqual($wrapper->field_file[0]->display
    ->value(), TRUE, 'File display value has been correctly set.');

  // Test adding a new file, the display-property has to be created
  // automatically.
  $wrapper->field_file[1]->file = $file;
  node_save($node);
  $node = node_load($node->nid, NULL, TRUE);
  $this
    ->assertEqual($file->fid, $wrapper->field_file[1]->file
    ->getIdentifier(), 'New file has been added.');

  // Test adding an invalid file-field item, i.e. without any file.
  try {
    $wrapper->field_file[] = array(
      'description' => 'test',
    );
    $this
      ->fail('Exception not thrown.');
  } catch (EntityMetadataWrapperException $e) {
    $this
      ->pass('Not valid file-field item has thrown an exception.');
  }

  // Test remove all file-field items.
  $wrapper->field_file = NULL;
  $this
    ->assertFalse($wrapper->field_file
    ->value(), 'Removed multiple file-field items.');
}