3 namespace Drupal\Tests\hal\Functional;
5 use Drupal\file\Entity\File;
6 use Drupal\Tests\BrowserTestBase;
9 * Tests that file entities can be denormalized in HAL.
12 * @see \Drupal\hal\Normalizer\FileEntityNormalizer
14 class FileDenormalizeTest extends BrowserTestBase {
21 public static $modules = ['hal', 'file', 'node'];
24 * Tests file entity denormalization.
26 public function testFileDenormalize() {
28 'filename' => 'test_1.txt',
29 'uri' => 'public://test_1.txt',
30 'filemime' => 'text/plain',
31 'status' => FILE_STATUS_PERMANENT,
33 // Create a new file entity.
34 $file = File::create($file_params);
35 file_put_contents($file->getFileUri(), 'hello world');
38 $serializer = \Drupal::service('serializer');
39 $normalized_data = $serializer->normalize($file, 'hal_json');
40 $denormalized = $serializer->denormalize($normalized_data, 'Drupal\file\Entity\File', 'hal_json');
42 $this->assertTrue($denormalized instanceof File, 'A File instance was created.');
44 $this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.');
45 $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
47 $this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found');
48 $this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.');
49 $this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.');
50 $this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.');
52 // Try to denormalize with the file uri only.
53 $file_name = 'test_2.txt';
54 $file_path = 'public://' . $file_name;
56 file_put_contents($file_path, 'hello world');
57 $file_uri = file_create_url($file_path);
61 ['value' => $file_uri],
65 $denormalized = $serializer->denormalize($data, 'Drupal\file\Entity\File', 'hal_json');
67 $this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.');
68 $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
70 $this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.');
71 $this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.');
72 $this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.');