You are here

public function SaveUploadTest::testNormal in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/file/tests/src/Functional/SaveUploadTest.php \Drupal\Tests\file\Functional\SaveUploadTest::testNormal()

Test the file_save_upload() function.

File

core/modules/file/tests/src/Functional/SaveUploadTest.php, line 96

Class

SaveUploadTest
Tests the file_save_upload() function.

Namespace

Drupal\Tests\file\Functional

Code

public function testNormal() {
  $max_fid_after = (int) \Drupal::entityQueryAggregate('file')
    ->aggregate('fid', 'max')
    ->execute()[0]['fid_max'];
  $this
    ->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
  $file1 = File::load($max_fid_after);
  $this
    ->assertInstanceOf(File::class, $file1);

  // MIME type of the uploaded image may be either image/jpeg or image/png.
  $this
    ->assertEqual(substr($file1
    ->getMimeType(), 0, 5), 'image', 'A MIME type was set.');

  // Reset the hook counters to get rid of the 'load' we just called.
  file_test_reset();

  // Upload a second file.
  $image2 = current($this
    ->drupalGetTestFiles('image'));
  $edit = [
    'files[file_test_upload]' => \Drupal::service('file_system')
      ->realpath($image2->uri),
  ];
  $this
    ->drupalPostForm('file-test/upload', $edit, t('Submit'));
  $this
    ->assertSession()
    ->statusCodeEquals(200);
  $this
    ->assertRaw(t('You WIN!'));
  $max_fid_after = (int) \Drupal::entityQueryAggregate('file')
    ->aggregate('fid', 'max')
    ->execute()[0]['fid_max'];

  // Check that the correct hooks were called.
  $this
    ->assertFileHooksCalled([
    'validate',
    'insert',
  ]);
  $file2 = File::load($max_fid_after);
  $this
    ->assertInstanceOf(File::class, $file2);

  // MIME type of the uploaded image may be either image/jpeg or image/png.
  $this
    ->assertEqual(substr($file2
    ->getMimeType(), 0, 5), 'image', 'A MIME type was set.');

  // Load both files using File::loadMultiple().
  $files = File::loadMultiple([
    $file1
      ->id(),
    $file2
      ->id(),
  ]);
  $this
    ->assertTrue(isset($files[$file1
    ->id()]), 'File was loaded successfully');
  $this
    ->assertTrue(isset($files[$file2
    ->id()]), 'File was loaded successfully');

  // Upload a third file to a subdirectory.
  $image3 = current($this
    ->drupalGetTestFiles('image'));
  $image3_realpath = \Drupal::service('file_system')
    ->realpath($image3->uri);
  $dir = $this
    ->randomMachineName();
  $edit = [
    'files[file_test_upload]' => $image3_realpath,
    'file_subdir' => $dir,
  ];
  $this
    ->drupalPostForm('file-test/upload', $edit, t('Submit'));
  $this
    ->assertSession()
    ->statusCodeEquals(200);
  $this
    ->assertRaw(t('You WIN!'));
  $this
    ->assertFileExists('temporary://' . $dir . '/' . trim(\Drupal::service('file_system')
    ->basename($image3_realpath)));
}