public function SaveUploadFormTest::testNormal in Drupal 9
Same name and namespace in other branches
- 8 core/modules/file/tests/src/Functional/SaveUploadFormTest.php \Drupal\Tests\file\Functional\SaveUploadFormTest::testNormal()
Tests the _file_save_upload_from_form() function.
File
- core/
modules/ file/ tests/ src/ Functional/ SaveUploadFormTest.php, line 105
Class
- SaveUploadFormTest
- Tests the _file_save_upload_from_form() function.
Namespace
Drupal\Tests\file\FunctionalCode
public function testNormal() {
$max_fid_after = (int) \Drupal::entityQueryAggregate('file')
->accessCheck(FALSE)
->aggregate('fid', 'max')
->execute()[0]['fid_max'];
// Verify that a new file was created.
$this
->assertGreaterThan($this->maxFidBefore, $max_fid_after);
$file1 = File::load($max_fid_after);
$this
->assertInstanceOf(File::class, $file1);
// MIME type of the uploaded image may be either image/jpeg or image/png.
$this
->assertEquals('image', substr($file1
->getMimeType(), 0, 5), 'A MIME type was set.');
// Reset the hook counters to get rid of the 'load' we just called.
file_test_reset();
// Upload a second file.
$image2 = current($this
->drupalGetTestFiles('image'));
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'files[file_test_upload][]' => $file_system
->realpath($image2->uri),
];
$this
->drupalGet('file-test/save_upload_from_form_test');
$this
->submitForm($edit, 'Submit');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains("You WIN!");
$max_fid_after = (int) \Drupal::entityQueryAggregate('file')
->accessCheck(FALSE)
->aggregate('fid', 'max')
->execute()[0]['fid_max'];
// Check that the correct hooks were called.
$this
->assertFileHooksCalled([
'validate',
'insert',
]);
$file2 = File::load($max_fid_after);
$this
->assertInstanceOf(File::class, $file2);
// MIME type of the uploaded image may be either image/jpeg or image/png.
$this
->assertEquals('image', substr($file2
->getMimeType(), 0, 5), 'A MIME type was set.');
// Load both files using File::loadMultiple().
$files = File::loadMultiple([
$file1
->id(),
$file2
->id(),
]);
$this
->assertTrue(isset($files[$file1
->id()]), 'File was loaded successfully');
$this
->assertTrue(isset($files[$file2
->id()]), 'File was loaded successfully');
// Upload a third file to a subdirectory.
$image3 = current($this
->drupalGetTestFiles('image'));
$image3_realpath = $file_system
->realpath($image3->uri);
$dir = $this
->randomMachineName();
$edit = [
'files[file_test_upload][]' => $image3_realpath,
'file_subdir' => $dir,
];
$this
->drupalGet('file-test/save_upload_from_form_test');
$this
->submitForm($edit, 'Submit');
$this
->assertSession()
->statusCodeEquals(200);
$this
->assertSession()
->pageTextContains("You WIN!");
$this
->assertFileExists('temporary://' . $dir . '/' . trim(\Drupal::service('file_system')
->basename($image3_realpath)));
}