function SaveUploadTest::testDuplicate

Same name and namespace in other branches
  1. 8.9.x core/modules/file/tests/src/Functional/SaveUploadTest.php \Drupal\Tests\file\Functional\SaveUploadTest::testDuplicate()
  2. 10 core/modules/file/tests/src/Functional/SaveUploadTest.php \Drupal\Tests\file\Functional\SaveUploadTest::testDuplicate()
  3. 11.x core/modules/file/tests/src/Functional/SaveUploadTest.php \Drupal\Tests\file\Functional\SaveUploadTest::testDuplicate()

Tests uploading a duplicate file.

File

core/modules/file/tests/src/Functional/SaveUploadTest.php, line 162

Class

SaveUploadTest
Tests the <a href="/api/drupal/core%21modules%21file%21file.module/function/file_save_upload/9" title="Saves file uploads to a new location." class="local">file_save_upload</a>() function.

Namespace

Drupal\Tests\file\Functional

Code

public function testDuplicate() {
    // It should not be possible to create two managed files with the same URI.
    $image1 = current($this->drupalGetTestFiles('image'));
    $edit = [
        'files[file_test_upload]' => \Drupal::service('file_system')->realpath($image1->uri),
    ];
    $this->drupalGet('file-test/upload');
    $this->submitForm($edit, 'Submit');
    $max_fid_after = (int) \Drupal::entityQueryAggregate('file')->accessCheck(FALSE)
        ->aggregate('fid', 'max')
        ->execute()[0]['fid_max'];
    $file1 = File::load($max_fid_after);
    // Simulate a race condition where two files are uploaded at almost the same
    // time, by removing the first uploaded file from disk (leaving the entry in
    // the file_managed table) before trying to upload another file with the
    // same name.
    unlink(\Drupal::service('file_system')->realpath($file1->getFileUri()));
    $image2 = $image1;
    $edit = [
        'files[file_test_upload]' => \Drupal::service('file_system')->realpath($image2->uri),
    ];
    $this->drupalGet('file-test/upload');
    $this->submitForm($edit, 'Submit');
    // Received a 200 response for posted test file.
    $this->assertSession()
        ->statusCodeEquals(200);
    $this->assertSession()
        ->pageTextContains("The file {$file1->getFileUri()} already exists. Enter a unique file URI.");
    $max_fid_before_duplicate = $max_fid_after;
    $max_fid_after = (int) \Drupal::entityQueryAggregate('file')->accessCheck(FALSE)
        ->aggregate('fid', 'max')
        ->execute()[0]['fid_max'];
    $this->assertEquals($max_fid_before_duplicate, $max_fid_after, 'A new managed file was not created.');
}

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