You are here

function SaveUploadTest::testNormal in Zircon Profile 8.0

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

Test the file_save_upload() function.

File

core/modules/file/src/Tests/SaveUploadTest.php, line 83
Contains \Drupal\file\Tests\SaveUploadTest.

Class

SaveUploadTest
Tests the file_save_upload() function.

Namespace

Drupal\file\Tests

Code

function testNormal() {
  $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')
    ->fetchField();
  $this
    ->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
  $file1 = File::load($max_fid_after);
  $this
    ->assertTrue($file1, 'Loaded the file.');

  // 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 = array(
    'files[file_test_upload]' => drupal_realpath($image2->uri),
  );
  $this
    ->drupalPostForm('file-test/upload', $edit, t('Submit'));
  $this
    ->assertResponse(200, 'Received a 200 response for posted test file.');
  $this
    ->assertRaw(t('You WIN!'));
  $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')
    ->fetchField();

  // Check that the correct hooks were called.
  $this
    ->assertFileHooksCalled(array(
    'validate',
    'insert',
  ));
  $file2 = File::load($max_fid_after);
  $this
    ->assertTrue($file2, 'Loaded the file');

  // 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(array(
    $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_realpath($image3->uri);
  $dir = $this
    ->randomMachineName();
  $edit = array(
    'files[file_test_upload]' => $image3_realpath,
    'file_subdir' => $dir,
  );
  $this
    ->drupalPostForm('file-test/upload', $edit, t('Submit'));
  $this
    ->assertResponse(200, 'Received a 200 response for posted test file.');
  $this
    ->assertRaw(t('You WIN!'));
  $this
    ->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
}