You are here

function FileSaveTest::testFileSave in SimpleTest 7

File

tests/file.test, line 1653
This provides SimpleTests for the core file handling functionality. These include FileValidateTest and FileSaveTest.

Class

FileSaveTest
Tests the file_save() function.

Code

function testFileSave() {

  // Create a new file object.
  $file = array(
    'uid' => 1,
    'filename' => 'druplicon.txt',
    'uri' => 'public://druplicon.txt',
    'filemime' => 'text/plain',
    'timestamp' => 1,
    'status' => FILE_STATUS_PERMANENT,
  );
  $file = (object) $file;
  file_put_contents($file->uri, 'hello world');

  // Save it, inserting a new record.
  $saved_file = file_save($file);

  // Check that the correct hooks were called.
  $this
    ->assertFileHooksCalled(array(
    'insert',
  ));
  $this
    ->assertNotNull($saved_file, t("Saving the file should give us back a file object."), 'File');
  $this
    ->assertTrue($saved_file->fid > 0, t("A new file ID is set when saving a new file to the database."), 'File');
  $loaded_file = db_query('SELECT * FROM {file} f WHERE f.fid = :fid', array(
    ':fid' => $saved_file->fid,
  ))
    ->fetch(PDO::FETCH_OBJ);
  $this
    ->assertNotNull($loaded_file, t("Record exists in the database."));
  $this
    ->assertEqual($loaded_file->status, $file->status, t("Status was saved correctly."));
  $this
    ->assertEqual($saved_file->filesize, filesize($file->uri), t("File size was set correctly."), 'File');
  $this
    ->assertTrue($saved_file->timestamp > 1, t("File size was set correctly."), 'File');

  // Resave the file, updating the existing record.
  file_test_reset();
  $saved_file->status = 7;
  $resaved_file = file_save($saved_file);

  // Check that the correct hooks were called.
  $this
    ->assertFileHooksCalled(array(
    'update',
  ));
  $this
    ->assertEqual($resaved_file->fid, $saved_file->fid, t("The file ID of an existing file is not changed when updating the database."), 'File');
  $this
    ->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, t("Timestamp didn't go backwards."), 'File');
  $loaded_file = db_query('SELECT * FROM {file} f WHERE f.fid = :fid', array(
    ':fid' => $saved_file->fid,
  ))
    ->fetch(PDO::FETCH_OBJ);
  $this
    ->assertNotNull($loaded_file, t("Record still exists in the database."), 'File');
  $this
    ->assertEqual($loaded_file->status, $saved_file->status, t("Status was saved correctly."));
}