You are here

public function FileEntityNormalizerTest::testFileFieldSerializePersist in File Entity (fieldable files) 8.2

Tests that file field is identical before and after de/serialization.

File

tests/src/Kernel/FileEntityNormalizerTest.php, line 64

Class

FileEntityNormalizerTest
Tests the File entity normalizer.

Namespace

Drupal\Tests\file_entity\Kernel

Code

public function testFileFieldSerializePersist() {

  // Create a node type.
  $node_type = NodeType::create(array(
    'type' => $this
      ->randomMachineName(),
  ));
  $node_type
    ->save();

  // Create a file.
  $file_name = $this
    ->randomMachineName() . '.txt';
  file_put_contents("public://{$file_name}", $this
    ->randomString());
  $file = File::create(array(
    'uri' => "public://{$file_name}",
  ));
  $file
    ->save();

  // Attach a file field to the node type.
  $file_field_storage = FieldStorageConfig::create(array(
    'type' => 'file',
    'entity_type' => 'node',
    'field_name' => 'field_file',
  ));
  $file_field_storage
    ->save();
  $file_field_instance = FieldConfig::create(array(
    'field_storage' => $file_field_storage,
    'entity_type' => 'node',
    'bundle' => $node_type
      ->id(),
  ));
  $file_field_instance
    ->save();

  // Create a node referencing the file.
  $node = Node::create(array(
    'title' => 'A node with a file',
    'type' => $node_type
      ->id(),
    'field_file' => array(
      'target_id' => $file
        ->id(),
      'display' => 0,
      'description' => 'An attached file',
    ),
    'status' => TRUE,
  ));

  // Export.
  $serialized = $this->container
    ->get('serializer')
    ->serialize($node, 'hal_json');

  // Import again.
  $deserialized = $this->container
    ->get('serializer')
    ->deserialize($serialized, 'Drupal\\node\\Entity\\Node', 'hal_json');

  // Compare.
  $this
    ->assertEquals($node
    ->toArray()['field_file'], $deserialized
    ->toArray()['field_file'], "File field persists.");
}