You are here

public function FileItemValidationTest::testFileValidationConstraint in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/tests/src/Kernel/FileItemValidationTest.php \Drupal\Tests\file\Kernel\FileItemValidationTest::testFileValidationConstraint()

@covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraint @covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraintValidator @dataProvider getFileTypes

File

core/modules/file/tests/src/Kernel/FileItemValidationTest.php, line 60
Contains \Drupal\Tests\file\Kernel\FileItemValidationTest.

Class

FileItemValidationTest
Tests that files referenced in file and image fields are always validated.

Namespace

Drupal\Tests\file\Kernel

Code

public function testFileValidationConstraint($file_type) {
  $field_storage = FieldStorageConfig::create([
    'field_name' => 'field_test_file',
    'entity_type' => 'entity_test',
    'type' => $file_type,
  ]);
  $field_storage
    ->save();
  $field = FieldConfig::create([
    'field_name' => 'field_test_file',
    'entity_type' => 'entity_test',
    'bundle' => 'entity_test',
    'settings' => [
      'max_filesize' => '2k',
      'file_extensions' => 'jpg|png',
    ],
  ]);
  $field
    ->save();
  vfsStream::setup('drupal_root');
  vfsStream::create([
    'sites' => [
      'default' => [
        'files' => [
          'test.txt' => str_repeat('a', 3000),
        ],
      ],
    ],
  ]);

  // Test for max filesize.
  $file = File::create([
    'uri' => 'vfs://drupal_root/sites/default/files/test.txt',
  ]);
  $file
    ->setPermanent();
  $file
    ->save();
  $entity_test = EntityTest::create([
    'uid' => $this->user
      ->id(),
    'field_test_file' => [
      'target_id' => $file
        ->id(),
    ],
  ]);
  $result = $entity_test
    ->validate();
  $this
    ->assertCount(2, $result);
  $this
    ->assertEquals('field_test_file.0', $result
    ->get(0)
    ->getPropertyPath());
  $this
    ->assertEquals('The file is <em class="placeholder">2.93 KB</em> exceeding the maximum file size of <em class="placeholder">2 KB</em>.', (string) $result
    ->get(0)
    ->getMessage());
  $this
    ->assertEquals('field_test_file.0', $result
    ->get(1)
    ->getPropertyPath());
  $this
    ->assertEquals('Only files with the following extensions are allowed: <em class="placeholder">jpg|png</em>.', (string) $result
    ->get(1)
    ->getMessage());
}