function CopyTest::testExistingError

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

Tests that copying over an existing file fails when instructed to do so.

@covers ::copy

File

core/modules/file/tests/src/Kernel/CopyTest.php, line 154

Class

CopyTest
Tests the file copy function.

Namespace

Drupal\Tests\file\Kernel

Code

public function testExistingError() {
    $contents = $this->randomMachineName(10);
    $source = $this->createFile();
    $target = $this->createFile(NULL, $contents);
    $this->assertDifferentFile($source, $target);
    // Clone the object so we don't have to worry about the function changing
    // our reference copy.
    try {
        $result = $this->fileRepository
            ->copy(clone $source, $target->getFileUri(), FileSystemInterface::EXISTS_ERROR);
        $this->fail('expected FileExistsException');
    } catch (FileExistsException $e) {
        // expected exception.
        $this->assertStringContainsString("could not be copied because a file by that name already exists in the destination directory", $e->getMessage());
    }
    // Check the contents were not changed.
    $this->assertEquals($contents, file_get_contents($target->getFileUri()), 'Contents of file were not altered.');
    // Check that the correct hooks were called.
    $this->assertFileHooksCalled([]);
    $this->assertFileUnchanged($source, File::load($source->id()));
    $this->assertFileUnchanged($target, File::load($target->id()));
}

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