function FileFieldValidateTest::testFileExtension
Same name in other branches
- 8.9.x core/modules/file/tests/src/Functional/FileFieldValidateTest.php \Drupal\Tests\file\Functional\FileFieldValidateTest::testFileExtension()
- 10 core/modules/file/tests/src/Functional/FileFieldValidateTest.php \Drupal\Tests\file\Functional\FileFieldValidateTest::testFileExtension()
- 11.x 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 130
Class
- FileFieldValidateTest
- Tests file field validation functions.
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.');
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.