function FileRepositoryTest::testExistingError

Same name in other branches
  1. 9 core/modules/file/tests/src/Kernel/FileRepositoryTest.php \Drupal\Tests\file\Kernel\FileRepositoryTest::testExistingError()
  2. 11.x core/modules/file/tests/src/Kernel/FileRepositoryTest.php \Drupal\Tests\file\Kernel\FileRepositoryTest::testExistingError()

Tests that writeData() fails overwriting an existing file.

@covers ::writeData

File

core/modules/file/tests/src/Kernel/FileRepositoryTest.php, line 145

Class

FileRepositoryTest
Tests the FileRepository.

Namespace

Drupal\Tests\file\Kernel

Code

public function testExistingError() : void {
    $contents = $this->randomMachineName();
    $existing = $this->createFile(NULL, $contents);
    // Check the overwrite error.
    try {
        $this->fileRepository
            ->writeData('asdf', $existing->getFileUri(), FileExists::Error);
        $this->fail('expected FileExistsException');
    } catch (FileExistsException $e) {
        $this->assertStringContainsString("could not be copied because a file by that name already exists in the destination directory", $e->getMessage());
    }
    $this->assertEquals($contents, file_get_contents($existing->getFileUri()), 'Contents of existing file were unchanged.');
    // Check that no hooks were called while failing.
    $this->assertFileHooksCalled([]);
    // Ensure that the existing file wasn't overwritten.
    $this->assertFileUnchanged($existing, File::load($existing->id()));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.