public function FileFieldValidateTest::testFileExtension in Drupal 10
Same name and namespace in other branches
- 8 core/modules/file/tests/src/Functional/FileFieldValidateTest.php \Drupal\Tests\file\Functional\FileFieldValidateTest::testFileExtension()
- 9 core/modules/file/tests/src/Functional/FileFieldValidateTest.php \Drupal\Tests\file\Functional\FileFieldValidateTest::testFileExtension()
Tests file extension checking.
File
- core/
modules/ file/ tests/ src/ Functional/ FileFieldValidateTest.php, line 128
Class
- FileFieldValidateTest
- Tests validation functions such as file type, max file size, max size per node, and required.
Namespace
Drupal\Tests\file\FunctionalCode
public function testFileExtension() {
$node_storage = $this->container
->get('entity_type.manager')
->getStorage('node');
$type_name = 'article';
$field_name = strtolower($this
->randomMachineName());
$this
->createFileField($field_name, 'node', $type_name);
$test_file = $this
->getTestFile('image');
[
,
$test_file_extension,
] = explode('.', $test_file
->getFilename());
// Disable extension checking.
$this
->updateFileField($field_name, $type_name, [
'file_extensions' => '',
]);
// Check that the file can be uploaded with no extension checking.
$nid = $this
->uploadNodeFile($test_file, $field_name, $type_name);
$node_storage
->resetCache([
$nid,
]);
$node = $node_storage
->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
$this
->assertFileExists($node_file
->getFileUri());
$this
->assertFileEntryExists($node_file, 'File entry exists after uploading a file with no extension checking.');
// Enable extension checking for text files.
$this
->updateFileField($field_name, $type_name, [
'file_extensions' => 'txt',
]);
// Check that the file with the wrong extension cannot be uploaded.
$this
->uploadNodeFile($test_file, $field_name, $type_name);
$this
->assertSession()
->pageTextContains("Only files with the following extensions are allowed: txt.");
// Enable extension checking for text and image files.
$this
->updateFileField($field_name, $type_name, [
'file_extensions' => "txt {$test_file_extension}",
]);
// Check that the file can be uploaded with extension checking.
$nid = $this
->uploadNodeFile($test_file, $field_name, $type_name);
$node_storage
->resetCache([
$nid,
]);
$node = $node_storage
->load($nid);
$node_file = File::load($node->{$field_name}->target_id);
$this
->assertFileExists($node_file
->getFileUri());
$this
->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
}