function FileUploadTest::testPostFileUploadDuplicateFile

Same name in other branches
  1. 9 core/modules/jsonapi/tests/src/Functional/FileUploadTest.php \Drupal\Tests\jsonapi\Functional\FileUploadTest::testPostFileUploadDuplicateFile()
  2. 8.9.x core/modules/jsonapi/tests/src/Functional/FileUploadTest.php \Drupal\Tests\jsonapi\Functional\FileUploadTest::testPostFileUploadDuplicateFile()
  3. 11.x core/modules/jsonapi/tests/src/Functional/FileUploadTest.php \Drupal\Tests\jsonapi\Functional\FileUploadTest::testPostFileUploadDuplicateFile()

Tests using the file upload POST route with a duplicate file name.

A new file should be created with a suffixed name.

File

core/modules/jsonapi/tests/src/Functional/FileUploadTest.php, line 403

Class

FileUploadTest
Tests binary data file upload route.

Namespace

Drupal\Tests\jsonapi\Functional

Code

public function testPostFileUploadDuplicateFile() : void {
    \Drupal::service('router.builder')->rebuild();
    $this->setUpAuthorization('POST');
    $this->config('jsonapi.settings')
        ->set('read_only', FALSE)
        ->save(TRUE);
    $uri = Url::fromUri('base:' . static::$postUri);
    // This request will have the default 'application/octet-stream' content
    // type header.
    $response = $this->fileRequest($uri, $this->testFileData);
    $this->assertSame(201, $response->getStatusCode());
    // Make the same request again. The file should be saved as a new file
    // entity that has the same file name but a suffixed file URI.
    $response = $this->fileRequest($uri, $this->testFileData);
    $this->assertSame(201, $response->getStatusCode());
    // Loading expected normalized data for file 2, the duplicate file.
    $expected = $this->getExpectedDocument(2, 'example_0.txt', TRUE);
    $this->assertResponseData($expected, $response);
    // Check the actual file data.
    $this->assertSame($this->testFileData, file_get_contents('public://foobar/example_0.txt'));
    // 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('public://foobar/example.txt'));
    // Make the same request again. The upload should fail validation.
    $response = $this->fileRequest($uri, $this->testFileData);
    $this->assertResourceErrorResponse(422, PlainTextOutput::renderFromHtml("Unprocessable Entity: file validation failed.\nThe file public://foobar/example.txt already exists. Enter a unique file URI."), $uri, $response);
}

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