You are here

public function ImageFieldValidateTest::testValid in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/image/tests/src/Functional/ImageFieldValidateTest.php \Drupal\Tests\image\Functional\ImageFieldValidateTest::testValid()
  2. 10 core/modules/image/tests/src/Functional/ImageFieldValidateTest.php \Drupal\Tests\image\Functional\ImageFieldValidateTest::testValid()

Test image validity.

File

core/modules/image/tests/src/Functional/ImageFieldValidateTest.php, line 28

Class

ImageFieldValidateTest
Tests validation functions such as min/max resolution.

Namespace

Drupal\Tests\image\Functional

Code

public function testValid() {
  $file_system = $this->container
    ->get('file_system');
  $image_files = $this
    ->drupalGetTestFiles('image');
  $field_name = strtolower($this
    ->randomMachineName());
  $this
    ->createImageField($field_name, 'article', [], [
    'file_directory' => 'test-upload',
  ]);
  $expected_path = 'public://test-upload';

  // Create alt text for the image.
  $alt = $this
    ->randomMachineName();

  // Create a node with a valid image.
  $node = $this
    ->uploadNodeImage($image_files[0], $field_name, 'article', $alt);
  $this
    ->assertFileExists($expected_path . '/' . $image_files[0]->filename);

  // Remove the image.
  $this
    ->drupalPostForm('node/' . $node . '/edit', [], t('Remove'));
  $this
    ->drupalPostForm(NULL, [], t('Save'));

  // Get invalid image test files from simpletest.
  $dir = 'core/tests/fixtures/files';
  $files = [];
  if (is_dir($dir)) {
    $files = $file_system
      ->scanDirectory($dir, '/invalid-img-.*/');
  }
  $invalid_image_files = [];
  foreach ($files as $file) {
    $invalid_image_files[$file->filename] = $file;
  }

  // Try uploading a zero-byte image.
  $zero_size_image = $invalid_image_files['invalid-img-zero-size.png'];
  $edit = [
    'files[' . $field_name . '_0]' => $file_system
      ->realpath($zero_size_image->uri),
  ];
  $this
    ->drupalPostForm('node/' . $node . '/edit', $edit, t('Upload'));
  $this
    ->assertFileNotExists($expected_path . '/' . $zero_size_image->filename);

  // Try uploading an invalid image.
  $invalid_image = $invalid_image_files['invalid-img-test.png'];
  $edit = [
    'files[' . $field_name . '_0]' => $file_system
      ->realpath($invalid_image->uri),
  ];
  $this
    ->drupalPostForm('node/' . $node . '/edit', $edit, t('Upload'));
  $this
    ->assertFileNotExists($expected_path . '/' . $invalid_image->filename);

  // Upload a valid image again.
  $valid_image = $image_files[0];
  $edit = [
    'files[' . $field_name . '_0]' => $file_system
      ->realpath($valid_image->uri),
  ];
  $this
    ->drupalPostForm('node/' . $node . '/edit', $edit, t('Upload'));
  $this
    ->assertFileExists($expected_path . '/' . $valid_image->filename);
}