public function FileEntityNormalizerTest::testFileSerialize in File Entity (fieldable files) 8.2
Tests that file entities are correctly serialized, including file contents.
File
- tests/
src/ Kernel/ FileEntityNormalizerTest.php, line 117
Class
- FileEntityNormalizerTest
- Tests the File entity normalizer.
Namespace
Drupal\Tests\file_entity\KernelCode
public function testFileSerialize() {
FileType::create(array(
'id' => 'undefined',
))
->save();
foreach ($this
->getTestFiles() as $file_obj) {
$file_contents = file_get_contents($file_obj->uri);
// Create file entity.
$file = File::create(array(
'uri' => $file_obj->uri,
'status' => TRUE,
));
$file
->save();
// Serialize.
$serialized = $this->container
->get('serializer')
->serialize($file, 'hal_json');
// Remove file.
$file
->delete();
$this->container
->get('entity_type.manager')
->getStorage('file')
->resetCache();
$this
->assertFalse(file_exists($file_obj->uri), "Deleted file {$file_obj->uri} from disk");
$this
->assertNull(File::load($file
->id()), "Deleted file {$file->id()} entity");
// Deserialize again.
$deserialized = $this->container
->get('serializer')
->deserialize($serialized, 'Drupal\\file\\Entity\\File', 'hal_json');
$deserialized
->save();
// Compare.
$files = File::loadMultiple();
$last_file = array_pop($files);
$this
->assertNotNull($last_file, 'A file entity was created');
$this
->assertTrue(file_exists($file_obj->uri), "A file was created on disk");
// Assert file is equal.
foreach (array(
'filename',
'uri',
'filemime',
'filesize',
'type',
) as $property) {
$this
->assertEquals($file
->get($property)->value, $last_file
->get($property)->value);
}
$this
->assertEquals($file
->get('type')->target_id, $last_file
->get('type')->target_id);
$this
->assertEquals($file_contents, file_get_contents($last_file
->getFileUri()), 'File contents are equal');
}
}