You are here

public function SaveUploadTest::testDuplicate in Drupal 10

Same name and namespace in other branches
  1. 8 core/modules/file/tests/src/Functional/SaveUploadTest.php \Drupal\Tests\file\Functional\SaveUploadTest::testDuplicate()
  2. 9 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 159

Class

SaveUploadTest
Tests the file_save_upload() 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.');
}