You are here

public function MoveTest::testExistingReplace in Drupal 8

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

Test replacement when moving onto a file that already exists.

File

core/modules/file/tests/src/Kernel/MoveTest.php, line 84

Class

MoveTest
Tests the file move function.

Namespace

Drupal\Tests\file\Kernel

Code

public function testExistingReplace() {

  // Setup a file to overwrite.
  $contents = $this
    ->randomMachineName(10);
  $source = $this
    ->createFile(NULL, $contents);
  $target = $this
    ->createFile();
  $this
    ->assertDifferentFile($source, $target);

  // Clone the object so we don't have to worry about the function changing
  // our reference copy.
  $result = file_move(clone $source, $target
    ->getFileUri(), FileSystemInterface::EXISTS_REPLACE);

  // Look at the results.
  $this
    ->assertEqual($contents, file_get_contents($result
    ->getFileUri()), 'Contents of file were overwritten.');
  $this
    ->assertFileNotExists($source
    ->getFileUri());
  $this
    ->assertNotEmpty($result, 'File moved successfully.');

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

  // Reload the file from the database and check that the changes were
  // actually saved.
  $loaded_result = File::load($result
    ->id());
  $this
    ->assertFileUnchanged($result, $loaded_result);

  // Check that target was re-used.
  $this
    ->assertSameFile($target, $loaded_result);

  // Source and result should be totally different.
  $this
    ->assertDifferentFile($source, $loaded_result);
}