function FileNameLengthConstraintValidatorTest::testFileValidateNameLength

Same name in other branches
  1. 11.x core/modules/file/tests/src/Kernel/Plugin/Validation/Constraint/FileNameLengthConstraintValidatorTest.php \Drupal\Tests\file\Kernel\Plugin\Validation\Constraint\FileNameLengthConstraintValidatorTest::testFileValidateNameLength()

This will ensure the filename length is valid.

@covers ::validate

File

core/modules/file/tests/src/Kernel/Plugin/Validation/Constraint/FileNameLengthConstraintValidatorTest.php, line 23

Class

FileNameLengthConstraintValidatorTest
Tests the FileNameLengthConstraintValidator.

Namespace

Drupal\Tests\file\Kernel\Plugin\Validation\Constraint

Code

public function testFileValidateNameLength() : void {
    // Create a new file entity.
    $file = File::create();
    // Add a filename with an allowed length and test it.
    $file->setFilename(str_repeat('x', 240));
    $this->assertEquals(240, strlen($file->getFilename()));
    $validators = [
        'FileNameLength' => [],
    ];
    $violations = $this->validator
        ->validate($file, $validators);
    $this->assertCount(0, $violations, 'No errors reported for 240 length filename.');
    // Add a filename with a length too long and test it.
    $file->setFilename(str_repeat('x', 241));
    $violations = $this->validator
        ->validate($file, $validators);
    $this->assertCount(1, $violations, 'An error reported for 241 length filename.');
    // Add a filename with an empty string and test it.
    $file->setFilename('');
    $violations = $this->validator
        ->validate($file, $validators);
    $this->assertCount(1, $violations, 'An error reported for 0 length filename.');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.