function FileFieldValidateTest::testFileExtension

Tests file extension checking.

File

drupal/core/modules/file/lib/Drupal/file/Tests/FileFieldValidateTest.php, line 128
Definition of Drupal\file\Tests\FileFieldValidateTest.

Class

FileFieldValidateTest
Tests various validations.

Namespace

Drupal\file\Tests

Code

function testFileExtension() {
  $type_name = 'article';
  $field_name = strtolower($this
    ->randomName());
  $this
    ->createFileField($field_name, $type_name);
  $field = field_info_field($field_name);
  $instance = field_info_instance('node', $field_name, $type_name);
  $test_file = $this
    ->getTestFile('image');
  list(, $test_file_extension) = explode('.', $test_file->filename);

  // 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 = node_load($nid, TRUE);
  $node_file = file_load($node->{$field_name}[LANGUAGE_NOT_SPECIFIED][0]['fid']);
  $this
    ->assertFileExists($node_file, t('File exists after uploading a file with no extension checking.'));
  $this
    ->assertFileEntryExists($node_file, t('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.
  $nid = $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, t('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 = node_load($nid, TRUE);
  $node_file = file_load($node->{$field_name}[LANGUAGE_NOT_SPECIFIED][0]['fid']);
  $this
    ->assertFileExists($node_file, t('File exists after uploading a file with extension checking.'));
  $this
    ->assertFileEntryExists($node_file, t('File entry exists after uploading a file with extension checking.'));

  // Remove our file field.
  field_delete_field($field_name);
}