You are here

function FileFieldValidateTest::testFileExtension in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/src/Tests/FileFieldValidateTest.php \Drupal\file\Tests\FileFieldValidateTest::testFileExtension()

Tests file extension checking.

File

core/modules/file/src/Tests/FileFieldValidateTest.php, line 122
Contains \Drupal\file\Tests\FileFieldValidateTest.

Class

FileFieldValidateTest
Tests validation functions such as file type, max file size, max size per node, and required.

Namespace

Drupal\file\Tests

Code

function testFileExtension() {
  $node_storage = $this->container
    ->get('entity.manager')
    ->getStorage('node');
  $type_name = 'article';
  $field_name = strtolower($this
    ->randomMachineName());
  $this
    ->createFileField($field_name, 'node', $type_name);
  $test_file = $this
    ->getTestFile('image');
  list(, $test_file_extension) = explode('.', $test_file
    ->getFilename());

  // Disable extension checking.
  $this
    ->updateFileField($field_name, $type_name, array(
    '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(array(
    $nid,
  ));
  $node = $node_storage
    ->load($nid);
  $node_file = File::load($node->{$field_name}->target_id);
  $this
    ->assertFileExists($node_file, 'File exists after uploading a file with no extension checking.');
  $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, array(
    'file_extensions' => 'txt',
  ));

  // Check that the file with the wrong extension cannot be uploaded.
  $this
    ->uploadNodeFile($test_file, $field_name, $type_name);
  $error_message = t('Only files with the following extensions are allowed: %files-allowed.', array(
    '%files-allowed' => 'txt',
  ));
  $this
    ->assertRaw($error_message, 'Node save failed when file uploaded with the wrong extension.');

  // Enable extension checking for text and image files.
  $this
    ->updateFileField($field_name, $type_name, array(
    '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(array(
    $nid,
  ));
  $node = $node_storage
    ->load($nid);
  $node_file = File::load($node->{$field_name}->target_id);
  $this
    ->assertFileExists($node_file, 'File exists after uploading a file with extension checking.');
  $this
    ->assertFileEntryExists($node_file, 'File entry exists after uploading a file with extension checking.');
}