You are here

public function SaveDataTest::testExistingReplace in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/file/tests/src/Kernel/SaveDataTest.php \Drupal\Tests\file\Kernel\SaveDataTest::testExistingReplace()

Test file_save_data() when replacing an existing file.

File

core/modules/file/tests/src/Kernel/SaveDataTest.php, line 100

Class

SaveDataTest
Tests the file_save_data() function.

Namespace

Drupal\Tests\file\Kernel

Code

public function testExistingReplace() {

  // Setup a file to overwrite.
  $existing = $this
    ->createFile();
  $contents = $this
    ->randomMachineName(8);
  $result = file_save_data($contents, $existing
    ->getFileUri(), FileSystemInterface::EXISTS_REPLACE);
  $this
    ->assertNotFalse($result, 'File saved successfully.');
  $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
  assert($stream_wrapper_manager instanceof StreamWrapperManagerInterface);
  $this
    ->assertEqual('public', $stream_wrapper_manager::getScheme($result
    ->getFileUri()), "File was placed in Drupal's files directory.");
  $this
    ->assertEqual($result
    ->getFilename(), $existing
    ->getFilename(), 'Filename was set to the basename of the existing file, rather than preserving the original name.');
  $this
    ->assertEqual($contents, file_get_contents($result
    ->getFileUri()), 'Contents of the file are correct.');
  $this
    ->assertEqual($result
    ->getMimeType(), 'application/octet-stream', 'A MIME type was set.');
  $this
    ->assertTrue($result
    ->isPermanent(), "The file's status was set to permanent.");

  // Check that the correct hooks were called.
  $this
    ->assertFileHooksCalled([
    'load',
    'update',
  ]);

  // Verify that the existing file was re-used.
  $this
    ->assertSameFile($existing, $result);

  // Verify that what was returned is what's in the database.
  $this
    ->assertFileUnchanged($result, File::load($result
    ->id()));
}