View source
<?php
function file_test_validator($file, $errors) {
return $errors;
}
function file_test_file_scan_callback($filepath = NULL) {
$files =& drupal_static(__FUNCTION__, array());
if (isset($filepath)) {
$files[] = $filepath;
}
else {
return $files;
}
}
function file_test_file_scan_callback_reset() {
drupal_static_reset('file_test_file_scan_callback');
}
class FileTestCase extends DrupalWebTestCase {
function assertFileUnchanged($before, $after) {
$this
->assertEqual($before->fid, $after->fid, t('File id is the same: %file1 == %file2.', array(
'%file1' => $before->fid,
'%file2' => $after->fid,
)), 'File unchanged');
$this
->assertEqual($before->uid, $after->uid, t('File owner is the same: %file1 == %file2.', array(
'%file1' => $before->uid,
'%file2' => $after->uid,
)), 'File unchanged');
$this
->assertEqual($before->filename, $after->filename, t('File name is the same: %file1 == %file2.', array(
'%file1' => $before->filename,
'%file2' => $after->filename,
)), 'File unchanged');
$this
->assertEqual($before->uri, $after->uri, t('File path is the same: %file1 == %file2.', array(
'%file1' => $before->uri,
'%file2' => $after->uri,
)), 'File unchanged');
$this
->assertEqual($before->filemime, $after->filemime, t('File MIME type is the same: %file1 == %file2.', array(
'%file1' => $before->filemime,
'%file2' => $after->filemime,
)), 'File unchanged');
$this
->assertEqual($before->filesize, $after->filesize, t('File size is the same: %file1 == %file2.', array(
'%file1' => $before->filesize,
'%file2' => $after->filesize,
)), 'File unchanged');
$this
->assertEqual($before->status, $after->status, t('File status is the same: %file1 == %file2.', array(
'%file1' => $before->status,
'%file2' => $after->status,
)), 'File unchanged');
}
function assertDifferentFile($file1, $file2) {
$this
->assertNotEqual($file1->fid, $file2->fid, t('Files have different ids: %file1 != %file2.', array(
'%file1' => $file1->fid,
'%file2' => $file2->fid,
)), 'Different file');
$this
->assertNotEqual($file1->uri, $file2->uri, t('Files have different paths: %file1 != %file2.', array(
'%file1' => $file1->uri,
'%file2' => $file2->uri,
)), 'Different file');
}
function assertSameFile($file1, $file2) {
$this
->assertEqual($file1->fid, $file2->fid, t('Files have the same ids: %file1 == %file2.', array(
'%file1' => $file1->fid,
'%file2-fid' => $file2->fid,
)), 'Same file');
$this
->assertEqual($file1->uri, $file2->uri, t('Files have the same path: %file1 == %file2.', array(
'%file1' => $file1->uri,
'%file2' => $file2->uri,
)), 'Same file');
}
function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
clearstatcache();
$actual_mode = fileperms($filepath) & 511;
if (!isset($message)) {
$message = t('Expected file permission to be %expected, actually were %actual.', array(
'%actual' => decoct($actual_mode),
'%expected' => decoct($expected_mode),
));
}
$this
->assertEqual($actual_mode, $expected_mode, $message);
}
function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
clearstatcache();
$actual_mode = fileperms($directory) & 511;
if (!isset($message)) {
$message = t('Expected directory permission to be %expected, actually were %actual.', array(
'%actual' => decoct($actual_mode),
'%expected' => decoct($expected_mode),
));
}
$this
->assertEqual($actual_mode, $expected_mode, $message);
}
function createDirectory($path = NULL) {
if (is_null($path)) {
$path = file_directory_path() . '/' . $this
->randomName();
}
$this
->assertTrue(drupal_mkdir($path) && is_dir($path), t('Directory was created successfully.'));
return $path;
}
function createFile($filepath = NULL, $contents = NULL, $scheme = 'public') {
if (is_null($filepath)) {
$filepath = $this
->randomName();
}
$filepath = $scheme . '://' . $filepath;
if (is_null($contents)) {
$contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
}
file_put_contents($filepath, $contents);
$this
->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');
$file = new stdClass();
$file->uri = $filepath;
$file->filename = basename($file->uri);
$file->filemime = 'text/plain';
$file->uid = 1;
$file->timestamp = REQUEST_TIME;
$file->filesize = filesize($file->uri);
$file->status = 0;
$this
->assertNotIdentical(drupal_write_record('file', $file), FALSE, t('The file was added to the database.'), 'Create test file');
return $file;
}
}
class FileHookTestCase extends FileTestCase {
function setUp() {
parent::setUp('file_test');
file_test_reset();
}
function assertFileHooksCalled($expected) {
$actual = array_keys(array_filter(file_test_get_all_calls()));
$uncalled = array_diff($expected, $actual);
if (count($uncalled)) {
$this
->assertTrue(FALSE, t('Expected hooks %expected to be called but %uncalled was not called.', array(
'%expected' => implode(', ', $expected),
'%uncalled' => implode(', ', $uncalled),
)));
}
else {
$this
->assertTrue(TRUE, t('All the expected hooks were called: %expected', array(
'%expected' => implode(', ', $expected),
)));
}
$unexpected = array_diff($actual, $expected);
if (count($unexpected)) {
$this
->assertTrue(FALSE, t('Unexpected hooks were called: %unexpected.', array(
'%unexpected' => implode(', ', $unexpected),
)));
}
else {
$this
->assertTrue(TRUE, t('No unexpected hooks were called.'));
}
}
function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
$actual_count = count(file_test_get_calls($hook));
if (is_null($message)) {
if ($actual_count == $expected_count) {
$message = t('hook_file_@name was called correctly.', array(
'@name' => $hook,
));
}
elseif ($expected_count == 0) {
$message = format_plural($actual_count, 'hook_file_@name was not expected to be called but was actually called once.', 'hook_file_@name was not expected to be called but was actually called @count times.', array(
'@name' => $hook,
'@count' => $actual_count,
));
}
else {
$message = t('hook_file_@name was expected to be called %expected times but was called %actual times.', array(
'@name' => $hook,
'%expected' => $expected_count,
'%actual' => $actual_count,
));
}
}
$this
->assertEqual($actual_count, $expected_count, $message);
}
}
class FileSpaceUsedTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File space used tests',
'description' => 'Tests the file_space_used() function.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp();
drupal_write_record('file', $file = array(
'uid' => 2,
'uri' => 'public://example1.txt',
'filesize' => 50,
'status' => FILE_STATUS_PERMANENT,
));
drupal_write_record('file', $file = array(
'uid' => 2,
'uri' => 'public://example2.txt',
'filesize' => 20,
'status' => FILE_STATUS_PERMANENT,
));
drupal_write_record('file', $file = array(
'uid' => 3,
'uri' => 'public://example3.txt',
'filesize' => 100,
'status' => FILE_STATUS_PERMANENT,
));
drupal_write_record('file', $file = array(
'uid' => 3,
'uri' => 'public://example4.txt',
'filesize' => 200,
'status' => FILE_STATUS_PERMANENT,
));
drupal_write_record('file', $file = array(
'uid' => 2,
'uri' => 'public://example5.txt',
'filesize' => 1,
'status' => 2 | 8,
));
drupal_write_record('file', $file = array(
'uid' => 3,
'uri' => 'public://example6.txt',
'filesize' => 3,
'status' => 2 | 4,
));
}
function testUser() {
$this
->assertEqual(file_space_used(2), 70, t("Found the size of the first user's files."));
$this
->assertEqual(file_space_used(3), 300, t("Found the size of the second user's files."));
$this
->assertEqual(file_space_used(), 370, t("Found the size of all user's files."));
}
function testStatus() {
$this
->assertEqual(file_space_used(NULL, 2), 4, t("Found the size of all user's files with status 2."));
$this
->assertEqual(file_space_used(NULL, 4), 3, t("Found the size of all user's files with status 4."));
$this
->assertEqual(file_space_used(NULL, 2 | 4), 3, t("Found the size of all user's files with status 6."));
}
function testUserAndStatus() {
$this
->assertEqual(file_space_used(1, 8), 0, t("Found the size of the admin user's files with status 8."));
$this
->assertEqual(file_space_used(2, 8), 1, t("Found the size of the first user's files with status 8."));
$this
->assertEqual(file_space_used(2, 2), 1, t("Found the size of the first user's files with status 2."));
$this
->assertEqual(file_space_used(3, 2), 3, t("Found the size of the second user's files with status 2."));
}
}
class FileValidatorTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'File validator tests',
'description' => 'Tests the functions used to validate uploaded files.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp();
$this->image = new stdClass();
$this->image->uri = 'misc/druplicon.png';
$this->image->filename = basename($this->image->uri);
$this->non_image = new stdClass();
$this->non_image->uri = 'misc/jquery.js';
$this->non_image->filename = basename($this->non_image->uri);
}
function testFileValidateExtensions() {
$file = new stdClass();
$file->filename = 'asdf.txt';
$errors = file_validate_extensions($file, 'asdf txt pork');
$this
->assertEqual(count($errors), 0, t('Valid extension accepted.'), 'File');
$file->filename = 'asdf.txt';
$errors = file_validate_extensions($file, 'exe png');
$this
->assertEqual(count($errors), 1, t('Invalid extension blocked.'), 'File');
}
function testFileValidateIsImage() {
$this
->assertTrue(file_exists($this->image->uri), t('The image being tested exists.'), 'File');
$errors = file_validate_is_image($this->image);
$this
->assertEqual(count($errors), 0, t('No error reported for our image file.'), 'File');
$this
->assertTrue(file_exists($this->non_image->uri), t('The non-image being tested exists.'), 'File');
$errors = file_validate_is_image($this->non_image);
$this
->assertEqual(count($errors), 1, t('An error reported for our non-image file.'), 'File');
}
function testFileValidateImageResolution() {
$errors = file_validate_image_resolution($this->non_image);
$this
->assertEqual(count($errors), 0, t("Shouldn't get any errors for a non-image file."), 'File');
$errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
$this
->assertEqual(count($errors), 0, t("Don't check the resolution on non files."), 'File');
$errors = file_validate_image_resolution($this->image);
$this
->assertEqual(count($errors), 0, t('No errors for an image when there is no minimum or maximum resolution.'), 'File');
$errors = file_validate_image_resolution($this->image, 0, '200x1');
$this
->assertEqual(count($errors), 1, t("Got an error for an image that wasn't wide enough."), 'File');
$errors = file_validate_image_resolution($this->image, 0, '1x200');
$this
->assertEqual(count($errors), 1, t("Got an error for an image that wasn't tall enough."), 'File');
$errors = file_validate_image_resolution($this->image, 0, '200x200');
$this
->assertEqual(count($errors), 1, t('Small images report an error.'), 'File');
if (image_get_toolkit()) {
$temp_dir = file_directory_path('temporary');
copy(drupal_realpath('misc/druplicon.png'), drupal_realpath($temp_dir) . '/druplicon.png');
$this->image->uri = $temp_dir . '/druplicon.png';
$errors = file_validate_image_resolution($this->image, '10x5');
$this
->assertEqual(count($errors), 0, t('No errors should be reported when an oversized image can be scaled down.'), 'File');
$info = image_get_info($this->image->uri);
$this
->assertTrue($info['width'] <= 10, t('Image scaled to correct width.'), 'File');
$this
->assertTrue($info['height'] <= 5, t('Image scaled to correct height.'), 'File');
unlink(drupal_realpath($temp_dir . '/druplicon.png'));
}
else {
$errors = file_validate_image_resolution($this->image, '5x10');
$this
->assertEqual(count($errors), 1, t("Oversize images that can't be scaled get an error."), 'File');
}
}
function testFileValidateNameLength() {
$file = new stdClass();
$file->filename = str_repeat('x', 240);
$this
->assertEqual(strlen($file->filename), 240);
$errors = file_validate_name_length($file);
$this
->assertEqual(count($errors), 0, t('No errors reported for 240 length filename.'), 'File');
$file->filename = str_repeat('x', 241);
$errors = file_validate_name_length($file);
$this
->assertEqual(count($errors), 1, t('An error reported for 241 length filename.'), 'File');
$file->filename = '';
$errors = file_validate_name_length($file);
$this
->assertEqual(count($errors), 1, t('An error reported for 0 length filename.'), 'File');
}
function testFileValidateSize() {
global $user;
$original_user = $user;
drupal_save_session(FALSE);
$user = user_load(1);
$file = new stdClass();
$file->filesize = 999999;
$errors = file_validate_size($file, 1, 1);
$this
->assertEqual(count($errors), 0, t('No size limits enforced on uid=1.'), 'File');
$user = $this
->drupalCreateUser();
$file = new stdClass();
$file->filesize = 1000;
$errors = file_validate_size($file, 0, 0);
$this
->assertEqual(count($errors), 0, t('No limits means no errors.'), 'File');
$errors = file_validate_size($file, 1, 0);
$this
->assertEqual(count($errors), 1, t('Error for the file being over the limit.'), 'File');
$errors = file_validate_size($file, 0, 1);
$this
->assertEqual(count($errors), 1, t('Error for the user being over their limit.'), 'File');
$errors = file_validate_size($file, 1, 1);
$this
->assertEqual(count($errors), 2, t('Errors for both the file and their limit.'), 'File');
$user = $original_user;
drupal_save_session(TRUE);
}
}
class FileUnmanagedSaveDataTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'Unmanaged file save data',
'description' => 'Tests the unmanaged file save data function.',
'group' => 'File API',
);
}
function testFileSaveData() {
$contents = $this
->randomName(8);
$filepath = file_unmanaged_save_data($contents);
$this
->assertTrue($filepath, t('Unnamed file saved correctly.'));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_stream_wrapper_valid_scheme($filepath)), t("File was placed in Drupal's files directory."));
$this
->assertEqual($contents, file_get_contents(drupal_realpath($filepath)), t('Contents of the file are correct.'));
$filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
$this
->assertTrue($filepath, t('Unnamed file saved correctly.'));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_uri_scheme($filepath)), t("File was placed in Drupal's files directory."));
$this
->assertEqual('asdf.txt', basename($filepath), t('File was named correctly.'));
$this
->assertEqual($contents, file_get_contents(drupal_realpath($filepath)), t('Contents of the file are correct.'));
$this
->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
}
}
class FileSaveUploadTest extends FileHookTestCase {
var $image;
var $maxFidBefore;
public static function getInfo() {
return array(
'name' => 'File uploading',
'description' => 'Tests the file uploading functions.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp();
$account = $this
->drupalCreateUser(array(
'access content',
));
$this
->drupalLogin($account);
$this->image = current($this
->drupalGetTestFiles('image'));
$this
->assertTrue(is_file($this->image->uri), t("The file we're going to upload exists."));
$this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file}')
->fetchField();
$edit = array(
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->uri),
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('Received a 200 response for posted test file.'));
$this
->assertRaw(t('You WIN!'), t('Found the success message.'));
$this
->assertFileHooksCalled(array(
'validate',
'insert',
));
file_test_reset();
}
function testNormal() {
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file}')
->fetchField();
$this
->assertTrue($max_fid_after > $this->maxFidBefore, t('A new file was created.'));
$file1 = file_load($max_fid_after);
$this
->assertTrue($file1, t('Loaded the file.'));
$this
->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
file_test_reset();
$max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file}')
->fetchField();
$image2 = current($this
->drupalGetTestFiles('image'));
$edit = array(
'files[file_test_upload]' => drupal_realpath($image2->uri),
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('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}')
->fetchField();
$this
->assertFileHooksCalled(array(
'validate',
'insert',
));
$file2 = file_load($max_fid_after);
$this
->assertTrue($file2);
$this
->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
$files = file_load_multiple(array(
$file1->fid,
$file2->fid,
));
$this
->assertTrue(isset($files[$file1->fid]), t('File was loaded successfully'));
$this
->assertTrue(isset($files[$file2->fid]), t('File was loaded successfully'));
$image3 = current($this
->drupalGetTestFiles('image'));
$image3_realpath = drupal_realpath($image3->uri);
$dir = $this
->randomName();
$edit = array(
'files[file_test_upload]' => $image3_realpath,
'file_subdir' => $dir,
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('Received a 200 response for posted test file.'));
$this
->assertRaw(t('You WIN!'));
$this
->assertTrue(is_file('temporary://' . $dir . '/' . trim(basename($image3_realpath))));
$this
->assertFalse(file_load_multiple(), t('No files were loaded.'));
}
function testExistingRename() {
$edit = array(
'file_test_replace' => FILE_EXISTS_RENAME,
'files[file_test_upload]' => drupal_realpath($this->image->uri),
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('Received a 200 response for posted test file.'));
$this
->assertRaw(t('You WIN!'), t('Found the success message.'));
$this
->assertFileHooksCalled(array(
'validate',
'insert',
));
}
function testExistingReplace() {
$edit = array(
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->uri),
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('Received a 200 response for posted test file.'));
$this
->assertRaw(t('You WIN!'), t('Found the success message.'));
$this
->assertFileHooksCalled(array(
'validate',
'load',
'update',
));
}
function testExistingError() {
$edit = array(
'file_test_replace' => FILE_EXISTS_ERROR,
'files[file_test_upload]' => drupal_realpath($this->image->uri),
);
$this
->drupalPost('file-test/upload', $edit, t('Submit'));
$this
->assertResponse(200, t('Received a 200 response for posted test file.'));
$this
->assertRaw(t('Epic upload FAIL!'), t('Found the failure message.'));
$this
->assertFileHooksCalled(array());
}
function testNoUpload() {
$this
->drupalPost('file-test/upload', array(), t('Submit'));
$this
->assertNoRaw(t('Epic upload FAIL!'), t('Failure message not found.'));
}
}
class FileDirectoryTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File paths and directories',
'description' => 'Tests operations dealing with directories.',
'group' => 'File API',
);
}
function testFileCheckDirectory() {
$directory = file_directory_path() . '/' . $this
->randomName() . '/' . $this
->randomName();
$this
->assertFalse(is_dir($directory), t('Directory does not exist prior to testing.'));
$this
->assertFalse(file_prepare_directory($directory, 0), t('Error reported for non-existing directory.'), 'File');
$this
->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), t('No error reported when creating a new directory.'), 'File');
$this
->assertTrue(is_dir($directory), t('Directory actually exists.'), 'File');
@chmod($directory, 0444);
$this
->assertFalse(file_prepare_directory($directory, 0), t('Error reported for a non-writeable directory.'), 'File');
$this
->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), t('No error reported when making directory writeable.'), 'File');
$this
->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
$directory = file_directory_path();
@unlink($directory . '/.htaccess');
$this
->assertFalse(is_file($directory . '/.htaccess'), t('Successfully removed the .htaccess file in the files directory.'), 'File');
file_ensure_htaccess();
$this
->assertTrue(is_file($directory . '/.htaccess'), t('Successfully re-created the .htaccess file in the files directory.'), 'File');
$file = file_get_contents(file_directory_path() . '/.htaccess');
$this
->assertEqual($file, "SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006\nOptions None\nOptions +FollowSymLinks", t('The .htaccess file contains the proper content.'), 'File');
}
function testFileDirectoryPath() {
$path = variable_get('file_public_path', '');
$this
->assertEqual($path, file_directory_path('public'), t('Properly returns the stored file directory path.'), 'File');
}
function testFileDirectoryTemp() {
variable_set('file_directory_temp', NULL);
$temp = file_directory_path('temporary');
$this
->assertTrue(!is_null($temp), t('Properly set and retrieved temp directory %directory.', array(
'%directory' => $temp,
)), 'File');
}
function testFileCreateNewFilepath() {
$basename = 'xyz.txt';
$directory = 'misc';
$original = $directory . '/' . $basename;
$path = file_create_filename($basename, $directory);
$this
->assertEqual($path, $original, t('New filepath %new equals %original.', array(
'%new' => $path,
'%original' => $original,
)), 'File');
$basename = 'druplicon.png';
$original = $directory . '/' . $basename;
$expected = $directory . '/druplicon_0.png';
$path = file_create_filename($basename, $directory);
$this
->assertEqual($path, $expected, t('Creating a new filepath from %original equals %new.', array(
'%new' => $path,
'%original' => $original,
)), 'File');
}
function testFileDestination() {
$destination = 'misc/xyz.txt';
$path = file_destination($destination, FILE_EXISTS_REPLACE);
$this
->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.'), 'File');
$path = file_destination($destination, FILE_EXISTS_RENAME);
$this
->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_RENAME.'), 'File');
$path = file_destination($destination, FILE_EXISTS_ERROR);
$this
->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_ERROR.'), 'File');
$destination = 'misc/druplicon.png';
$path = file_destination($destination, FILE_EXISTS_REPLACE);
$this
->assertEqual($path, $destination, t('Existing filepath destination remains the same with FILE_EXISTS_REPLACE.'), 'File');
$path = file_destination($destination, FILE_EXISTS_RENAME);
$this
->assertNotEqual($path, $destination, t('A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.'), 'File');
$path = file_destination($destination, FILE_EXISTS_ERROR);
$this
->assertEqual($path, FALSE, t('An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.'), 'File');
}
}
class FileScanDirectoryTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File scan directory',
'description' => 'Tests the file_scan_directory() function.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp();
$this->path = $this->originalFileDirectory . '/simpletest';
}
function testReturn() {
$all_files = file_scan_directory($this->path, '/^javascript-/');
ksort($all_files);
$this
->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
$file = reset($all_files);
$this
->assertEqual(key($all_files), $file->uri, t('Correct array key was used for the first returned file.'));
$this
->assertEqual($file->uri, $this->path . '/javascript-1.txt', t('First file name was set correctly.'));
$this
->assertEqual($file->filename, 'javascript-1.txt', t('First basename was set correctly'));
$this
->assertEqual($file->name, 'javascript-1', t('First name was set correctly.'));
$file = next($all_files);
$this
->assertEqual(key($all_files), $file->uri, t('Correct array key was used for the second returned file.'));
$this
->assertEqual($file->uri, $this->path . '/javascript-2.script', t('Second file name was set correctly.'));
$this
->assertEqual($file->filename, 'javascript-2.script', t('Second basename was set correctly'));
$this
->assertEqual($file->name, 'javascript-2', t('Second name was set correctly.'));
}
function testOptionCallback() {
$all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array(
'callback' => 'file_test_file_scan_callback',
));
$this
->assertEqual(0, count($all_files), t('No files were found.'));
$results = file_test_file_scan_callback();
file_test_file_scan_callback_reset();
$this
->assertEqual(0, count($results), t('No files were passed to the callback.'));
$all_files = file_scan_directory($this->path, '/^javascript-/', array(
'callback' => 'file_test_file_scan_callback',
));
$this
->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
$results = file_test_file_scan_callback();
file_test_file_scan_callback_reset();
$this
->assertEqual(2, count($results), t('Files were passed to the callback.'));
}
function testOptionNoMask() {
$all_files = file_scan_directory($this->path, '/^javascript-/');
$this
->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));
$filtered_files = file_scan_directory($this->path, '/^javascript-/', array(
'nomask' => '/.script$/',
));
$this
->assertEqual(1, count($filtered_files), t('Filtered correctly.'));
}
function testOptionKey() {
$expected = array(
$this->path . '/javascript-1.txt',
$this->path . '/javascript-2.script',
);
$actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array(
'key' => 'filepath',
)));
sort($actual);
$this
->assertEqual($expected, $actual, t('Returned the correct values for the filename key.'));
$expected = array(
'javascript-1.txt',
'javascript-2.script',
);
$actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array(
'key' => 'filename',
)));
sort($actual);
$this
->assertEqual($expected, $actual, t('Returned the correct values for the basename key.'));
$expected = array(
'javascript-1',
'javascript-2',
);
$actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array(
'key' => 'name',
)));
sort($actual);
$this
->assertEqual($expected, $actual, t('Returned the correct values for the name key.'));
$expected = array(
$this->path . '/javascript-1.txt',
$this->path . '/javascript-2.script',
);
$actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array(
'key' => 'INVALID',
)));
sort($actual);
$this
->assertEqual($expected, $actual, t('An invalid key defaulted back to the default.'));
}
function testOptionRecurse() {
$files = file_scan_directory($this->originalFileDirectory, '/^javascript-/', array(
'recurse' => FALSE,
));
$this
->assertTrue(empty($files), t("Without recursion couldn't find javascript files."));
$files = file_scan_directory($this->originalFileDirectory, '/^javascript-/', array(
'recurse' => TRUE,
));
$this
->assertEqual(2, count($files), t('With recursion we found the expected javascript files.'));
}
function testOptionMinDepth() {
$files = file_scan_directory($this->path, '/^javascript-/', array(
'min_depth' => 0,
));
$this
->assertEqual(2, count($files), t('No minimum-depth gets files in current directory.'));
$files = file_scan_directory($this->path, '/^javascript-/', array(
'min_depth' => 1,
));
$this
->assertTrue(empty($files), t("Minimum-depth of 1 successfully excludes files from current directory."));
}
}
class FileUnmanagedDeleteTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'Unmanaged file delete',
'description' => 'Tests the unmanaged file delete function.',
'group' => 'File API',
);
}
function testNormal() {
$file = $this
->createFile();
$this
->assertTrue(file_unmanaged_delete($file->uri), t('Deleted worked.'));
$this
->assertFalse(file_exists($file->uri), t('Test file has actually been deleted.'));
}
function testMissing() {
$this
->assertTrue(file_unmanaged_delete(file_directory_path() . '/' . $this
->randomName()), t('Returns true when deleting a non-existent file.'));
}
function testDirectory() {
$directory = $this
->createDirectory();
$this
->assertFalse(file_unmanaged_delete($directory), t('Could not delete the delete directory.'));
$this
->assertTrue(file_exists($directory), t('Directory has not been deleted.'));
}
}
class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'Unmanaged recursive file delete',
'description' => 'Tests the unmanaged file delete recursive function.',
'group' => 'File API',
);
}
function testSingleFile() {
$filepath = file_directory_path() . '/' . $this
->randomName();
file_put_contents($filepath, '');
$this
->assertTrue(file_unmanaged_delete_recursive($filepath), t('Function reported success.'));
$this
->assertFalse(file_exists($filepath), t('Test file has been deleted.'));
}
function testEmptyDirectory() {
$directory = $this
->createDirectory();
$this
->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
$this
->assertFalse(file_exists($directory), t('Directory has been deleted.'));
}
function testDirectory() {
$directory = $this
->createDirectory();
$filepathA = $directory . '/A';
$filepathB = $directory . '/B';
file_put_contents($filepathA, '');
file_put_contents($filepathB, '');
$this
->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
$this
->assertFalse(file_exists($filepathA), t('Test file A has been deleted.'));
$this
->assertFalse(file_exists($filepathB), t('Test file B has been deleted.'));
$this
->assertFalse(file_exists($directory), t('Directory has been deleted.'));
}
function testSubDirectory() {
$directory = $this
->createDirectory();
$subdirectory = $this
->createDirectory($directory . '/sub');
$filepathA = $directory . '/A';
$filepathB = $subdirectory . '/B';
file_put_contents($filepathA, '');
file_put_contents($filepathB, '');
$this
->assertTrue(file_unmanaged_delete_recursive($directory), t('Function reported success.'));
$this
->assertFalse(file_exists($filepathA), t('Test file A has been deleted.'));
$this
->assertFalse(file_exists($filepathB), t('Test file B has been deleted.'));
$this
->assertFalse(file_exists($subdirectory), t('Subdirectory has been deleted.'));
$this
->assertFalse(file_exists($directory), t('Directory has been deleted.'));
}
}
class FileUnmanagedMoveTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'Unmanaged file moving',
'description' => 'Tests the unmanaged file move function.',
'group' => 'File API',
);
}
function testNormal() {
$file = $this
->createFile();
$desired_filepath = 'public://' . $this
->randomName();
$new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
$this
->assertTrue($new_filepath, t('Move was successful.'));
$this
->assertEqual($new_filepath, $desired_filepath, t('Returned expected filepath.'));
$this
->assertTrue(file_exists($new_filepath), t('File exists at the new location.'));
$this
->assertFalse(file_exists($file->uri), t('No file remains at the old location.'));
$this
->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
$desired_filepath = 'public://' . $this
->randomName();
$this
->assertTrue(file_exists($new_filepath), t('File exists before moving.'));
$this
->assertTrue(file_put_contents($desired_filepath, ' '), t('Created a file so a rename will have to happen.'));
$newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
$this
->assertTrue($newer_filepath, t('Move was successful.'));
$this
->assertNotEqual($newer_filepath, $desired_filepath, t('Returned expected filepath.'));
$this
->assertTrue(file_exists($newer_filepath), t('File exists at the new location.'));
$this
->assertFalse(file_exists($new_filepath), t('No file remains at the old location.'));
$this
->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
}
function testMissing() {
$new_filepath = file_unmanaged_move($this
->randomName(), $this
->randomName());
$this
->assertFalse($new_filepath, t('Moving a missing file fails.'));
}
function testOverwriteSelf() {
$file = $this
->createFile();
$new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
$this
->assertFalse($new_filepath, t('Moving onto itself without renaming fails.'));
$this
->assertTrue(file_exists($file->uri), t('File exists after moving onto itself.'));
$new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
$this
->assertTrue($new_filepath, t('Moving onto itself with renaming works.'));
$this
->assertFalse(file_exists($file->uri), t('Original file has been removed.'));
$this
->assertTrue(file_exists($new_filepath), t('File exists after moving onto itself.'));
}
}
class FileUnmanagedCopyTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'Unmanaged file copying',
'description' => 'Tests the unmanaged file copy function.',
'group' => 'File API',
);
}
function testNormal() {
$file = $this
->createFile();
$desired_filepath = 'public://' . $this
->randomName();
$new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
$this
->assertTrue($new_filepath, t('Copy was successful.'));
$this
->assertEqual($new_filepath, $desired_filepath, t('Returned expected filepath.'));
$this
->assertTrue(file_exists($file->uri), t('Original file remains.'));
$this
->assertTrue(file_exists($new_filepath), t('New file exists.'));
$this
->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
$desired_filepath = 'public://' . $this
->randomName();
$this
->assertTrue(file_put_contents($desired_filepath, ' '), t('Created a file so a rename will have to happen.'));
$newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
$this
->assertTrue($newer_filepath, t('Copy was successful.'));
$this
->assertNotEqual($newer_filepath, $desired_filepath, t('Returned expected filepath.'));
$this
->assertTrue(file_exists($file->uri), t('Original file remains.'));
$this
->assertTrue(file_exists($newer_filepath), t('New file exists.'));
$this
->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
}
function testNonExistent() {
$desired_filepath = $this
->randomName();
$this
->assertFalse(file_exists($desired_filepath), t("Randomly named file doesn't exists."));
$new_filepath = file_unmanaged_copy($desired_filepath, $this
->randomName());
$this
->assertFalse($new_filepath, t('Copying a missing file fails.'));
}
function testOverwriteSelf() {
$file = $this
->createFile();
$new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
$this
->assertTrue($new_filepath, t('Copying onto itself with renaming works.'));
$this
->assertNotEqual($new_filepath, $file->uri, t('Copied file has a new name.'));
$this
->assertTrue(file_exists($file->uri), t('Original file exists after copying onto itself.'));
$this
->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
$this
->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
$new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
$this
->assertFalse($new_filepath, t('Copying onto itself without renaming fails.'));
$this
->assertTrue(file_exists($file->uri), t('File exists after copying onto itself.'));
$new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
$this
->assertFalse($new_filepath, t('Copying onto itself fails.'));
$this
->assertTrue(file_exists($file->uri), t('File exists after copying onto itself.'));
$new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
$this
->assertTrue($new_filepath, t('Copying into same directory works.'));
$this
->assertNotEqual($new_filepath, $file->uri, t('Copied file has a new name.'));
$this
->assertTrue(file_exists($file->uri), t('Original file exists after copying onto itself.'));
$this
->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
$this
->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
}
}
class FileDeleteTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File delete',
'description' => 'Tests the file delete function.',
'group' => 'File API',
);
}
function testNormal() {
$file = $this
->createFile();
$this
->assertTrue(is_file($file->uri), t("File exists."));
$this
->assertIdentical(file_delete($file), TRUE, t("Delete worked."));
$this
->assertFileHooksCalled(array(
'references',
'delete',
));
$this
->assertFalse(file_exists($file->uri), t("Test file has actually been deleted."));
$this
->assertFalse(file_load($file->fid), t('File was removed from the database.'));
}
}
class FileMoveTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File moving',
'description' => 'Tests the file move function.',
'group' => 'File API',
);
}
function testNormal() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$desired_filepath = 'public://' . $this
->randomName();
$result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
$this
->assertTrue($result, t('File moved sucessfully.'));
$this
->assertFalse(file_exists($source->uri));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file correctly written.'));
$this
->assertFileHooksCalled(array(
'move',
'update',
));
$this
->assertEqual($source->fid, $result->fid, t("Source file id's' %fid is unchanged after move.", array(
'%fid' => $source->fid,
)));
$loaded_file = file_load($result->fid, TRUE);
$this
->assertTrue($loaded_file, t('File can be loaded from the database.'));
$this
->assertFileUnchanged($result, $loaded_file);
}
function testExistingRename() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$target = $this
->createFile();
$this
->assertDifferentFile($source, $target);
$result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
$this
->assertTrue($result, t('File moved sucessfully.'));
$this
->assertFalse(file_exists($source->uri));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file correctly written.'));
$this
->assertFileHooksCalled(array(
'move',
'update',
));
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
$this
->assertFileUnchanged($target, file_load($target->fid, TRUE));
$this
->assertDifferentFile($target, $result);
$loaded_source = file_load($source->fid, TRUE);
$this
->assertEqual($loaded_source->fid, $result->fid, t("Returned file's id matches the source."));
$this
->assertNotEqual($loaded_source->uri, $source->uri, t("Returned file path has changed from the original."));
}
function testExistingReplace() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$target = $this
->createFile();
$this
->assertDifferentFile($source, $target);
$result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were overwritten.'));
$this
->assertFalse(file_exists($source->uri));
$this
->assertTrue($result, t('File moved sucessfully.'));
$this
->assertFileHooksCalled(array(
'move',
'update',
'delete',
'references',
'load',
));
$loaded_result = file_load($result->fid, TRUE);
$this
->assertFileUnchanged($result, $loaded_result);
$this
->assertSameFile($target, $loaded_result);
$this
->assertDifferentFile($source, $loaded_result);
}
function testExistingReplaceSelf() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
$this
->assertFalse($result, t('File move failed.'));
$this
->assertEqual($contents, file_get_contents($source->uri), t('Contents of file were not altered.'));
$this
->assertFileHooksCalled(array());
$this
->assertFileUnchanged($source, file_load($source->fid, TRUE));
}
function testExistingError() {
$contents = $this
->randomName(10);
$source = $this
->createFile();
$target = $this
->createFile(NULL, $contents);
$this
->assertDifferentFile($source, $target);
$result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
$this
->assertFalse($result, t('File move failed.'));
$this
->assertTrue(file_exists($source->uri));
$this
->assertEqual($contents, file_get_contents($target->uri), t('Contents of file were not altered.'));
$this
->assertFileHooksCalled(array());
$this
->assertFileUnchanged($source, file_load($source->fid, TRUE));
$this
->assertFileUnchanged($target, file_load($target->fid, TRUE));
}
}
class FileCopyTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File copying',
'description' => 'Tests the file copy function.',
'group' => 'File API',
);
}
function testNormal() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$desired_uri = 'public://' . $this
->randomName();
$result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
$this
->assertTrue($result, t('File copied sucessfully.'));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were copied correctly.'));
$this
->assertFileHooksCalled(array(
'copy',
'insert',
));
$this
->assertDifferentFile($source, $result);
$this
->assertEqual($result->uri, $desired_uri, t('The copied file object has the desired filepath.'));
$this
->assertTrue(file_exists($source->uri), t('The original file still exists.'));
$this
->assertTrue(file_exists($result->uri), t('The copied file exists.'));
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
}
function testExistingRename() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$target = $this
->createFile();
$this
->assertDifferentFile($source, $target);
$result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
$this
->assertTrue($result, t('File copied sucessfully.'));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were copied correctly.'));
$this
->assertNotEqual($result->uri, $source->uri, t('Returned file path has changed from the original.'));
$this
->assertFileHooksCalled(array(
'copy',
'insert',
));
$loaded_source = file_load($source->fid, TRUE);
$loaded_target = file_load($target->fid, TRUE);
$loaded_result = file_load($result->fid, TRUE);
$this
->assertFileUnchanged($source, $loaded_source);
$this
->assertFileUnchanged($result, $loaded_result);
$this
->assertDifferentFile($loaded_source, $loaded_target);
$this
->assertDifferentFile($loaded_target, $loaded_result);
$this
->assertDifferentFile($loaded_source, $loaded_result);
}
function testExistingReplace() {
$contents = $this
->randomName(10);
$source = $this
->createFile(NULL, $contents);
$target = $this
->createFile();
$this
->assertDifferentFile($source, $target);
$result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
$this
->assertTrue($result, t('File copied sucessfully.'));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of file were overwritten.'));
$this
->assertDifferentFile($source, $result);
$this
->assertFileHooksCalled(array(
'load',
'copy',
'update',
));
$loaded_source = file_load($source->fid, TRUE);
$loaded_target = file_load($target->fid, TRUE);
$loaded_result = file_load($result->fid, TRUE);
$this
->assertFileUnchanged($source, $loaded_source);
$this
->assertFileUnchanged($result, $loaded_result);
$this
->assertFileUnchanged($loaded_target, $loaded_result);
}
function testExistingError() {
$contents = $this
->randomName(10);
$source = $this
->createFile();
$target = $this
->createFile(NULL, $contents);
$this
->assertDifferentFile($source, $target);
$result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
$this
->assertFalse($result, t('File copy failed.'));
$this
->assertEqual($contents, file_get_contents($target->uri), t('Contents of file were not altered.'));
$this
->assertFileHooksCalled(array());
$this
->assertFileUnchanged($source, file_load($source->fid, TRUE));
$this
->assertFileUnchanged($target, file_load($target->fid, TRUE));
}
}
class FileLoadTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File loading',
'description' => 'Tests the file_load() function.',
'group' => 'File API',
);
}
function testLoadMissingFid() {
$this
->assertFalse(file_load(-1), t("Try to load an invalid fid fails."));
$this
->assertFileHooksCalled(array());
}
function testLoadMissingFilepath() {
$this
->assertFalse(reset(file_load_multiple(array(), array(
'uri' => 'foobar://misc/druplicon.png',
))), t("Try to load a file that doesn't exist in the database fails."));
$this
->assertFileHooksCalled(array());
}
function testLoadInvalidStatus() {
$this
->assertFalse(reset(file_load_multiple(array(), array(
'status' => -99,
))), t("Trying to load a file with an invalid status fails."));
$this
->assertFileHooksCalled(array());
}
function testSingleValues() {
$file = $this
->createFile('druplicon.txt', NULL, 'public');
$by_fid_file = file_load($file->fid);
$this
->assertFileHookCalled('load');
$this
->assertTrue(is_object($by_fid_file), t('file_load() returned an object.'));
$this
->assertEqual($by_fid_file->fid, $file->fid, t("Loading by fid got the same fid."), 'File');
$this
->assertEqual($by_fid_file->uri, $file->uri, t("Loading by fid got the correct filepath."), 'File');
$this
->assertEqual($by_fid_file->filename, $file->filename, t("Loading by fid got the correct filename."), 'File');
$this
->assertEqual($by_fid_file->filemime, $file->filemime, t("Loading by fid got the correct MIME type."), 'File');
$this
->assertEqual($by_fid_file->status, $file->status, t("Loading by fid got the correct status."), 'File');
$this
->assertTrue($by_fid_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
}
function testMultiple() {
$file = $this
->createFile('druplicon.txt', NULL, 'public');
file_test_reset();
$by_path_files = file_load_multiple(array(), array(
'uri' => $file->uri,
));
$this
->assertFileHookCalled('load');
$this
->assertEqual(1, count($by_path_files), t('file_load_multiple() returned an array of the correct size.'));
$by_path_file = reset($by_path_files);
$this
->assertTrue($by_path_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
$this
->assertEqual($by_path_file->fid, $file->fid, t("Loading by filepath got the correct fid."), 'File');
file_test_reset();
$by_fid_files = file_load_multiple(array(
$file->fid,
), array());
$this
->assertFileHookCalled('load');
$this
->assertEqual(1, count($by_fid_files), t('file_load_multiple() returned an array of the correct size.'));
$by_fid_file = reset($by_fid_files);
$this
->assertTrue($by_fid_file->file_test['loaded'], t('file_test_file_load() was able to modify the file during load.'));
$this
->assertEqual($by_fid_file->uri, $file->uri, t("Loading by fid got the correct filepath."), 'File');
}
}
class FileSaveTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File saving',
'description' => 'Tests the file_save() function.',
'group' => 'File API',
);
}
function testFileSave() {
$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');
$saved_file = file_save($file);
$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');
file_test_reset();
$saved_file->status = 7;
$resaved_file = file_save($saved_file);
$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."));
}
}
class FileValidateTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File validate',
'description' => 'Tests the file_validate() function.',
'group' => 'File API',
);
}
function testCallerValidation() {
$file = $this
->createFile();
$this
->assertEqual(file_validate($file, array()), array(), t('Validating an empty array works succesfully.'));
$this
->assertFileHooksCalled(array(
'validate',
));
file_test_reset();
file_test_set_return('validate', array());
$passing = array(
'file_test_validator' => array(
array(),
),
);
$this
->assertEqual(file_validate($file, $passing), array(), t('Validating passes.'));
$this
->assertFileHooksCalled(array(
'validate',
));
file_test_reset();
file_test_set_return('validate', array(
'Epic fail',
));
$failing = array(
'file_test_validator' => array(
array(
'Failed',
'Badly',
),
),
);
$this
->assertEqual(file_validate($file, $failing), array(
'Failed',
'Badly',
'Epic fail',
), t('Validating returns errors.'));
$this
->assertFileHooksCalled(array(
'validate',
));
}
}
class FileSaveDataTest extends FileHookTestCase {
public static function getInfo() {
return array(
'name' => 'File save data',
'description' => 'Tests the file save data function.',
'group' => 'File API',
);
}
function testWithoutFilename() {
$contents = $this
->randomName(8);
$result = file_save_data($contents);
$this
->assertTrue($result, t('Unnamed file saved correctly.'));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_stream_wrapper_valid_scheme($result->uri)), t("File was placed in Drupal's files directory."));
$this
->assertEqual($result->filename, basename($result->uri), t("Filename was set to the file's basename."));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
$this
->assertEqual($result->filemime, 'application/octet-stream', t('A MIME type was set.'));
$this
->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
$this
->assertFileHooksCalled(array(
'insert',
));
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
}
function testWithFilename() {
$contents = $this
->randomName(8);
$result = file_save_data($contents, 'public://' . 'asdf.txt');
$this
->assertTrue($result, t('Unnamed file saved correctly.'));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_stream_wrapper_valid_scheme($result->uri)), t("File was placed in Drupal's files directory."));
$this
->assertEqual('asdf.txt', basename($result->uri), t('File was named correctly.'));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
$this
->assertEqual($result->filemime, 'text/plain', t('A MIME type was set.'));
$this
->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
$this
->assertFileHooksCalled(array(
'insert',
));
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
}
function testExistingRename() {
$existing = $this
->createFile();
$contents = $this
->randomName(8);
$result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
$this
->assertTrue($result, t("File saved sucessfully."));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_stream_wrapper_valid_scheme($result->uri)), t("File was placed in Drupal's files directory."));
$this
->assertEqual($result->filename, $existing->filename, t("Filename was set to the basename of the source, rather than that of the renamed file."));
$this
->assertEqual($contents, file_get_contents($result->uri), t("Contents of the file are correct."));
$this
->assertEqual($result->filemime, 'application/octet-stream', t("A MIME type was set."));
$this
->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
$this
->assertFileHooksCalled(array(
'insert',
));
$this
->assertDifferentFile($existing, $result);
$this
->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
}
function testExistingReplace() {
$existing = $this
->createFile();
$contents = $this
->randomName(8);
$result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
$this
->assertTrue($result, t('File saved sucessfully.'));
$this
->assertEqual(file_directory_path('public'), file_directory_path(file_stream_wrapper_valid_scheme($result->uri)), t("File was placed in Drupal's files directory."));
$this
->assertEqual($result->filename, $existing->filename, t('Filename was set to the basename of the existing file, rather than preserving the original name.'));
$this
->assertEqual($contents, file_get_contents($result->uri), t('Contents of the file are correct.'));
$this
->assertEqual($result->filemime, 'application/octet-stream', t('A MIME type was set.'));
$this
->assertEqual($result->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));
$this
->assertFileHooksCalled(array(
'load',
'update',
));
$this
->assertSameFile($existing, $result);
$this
->assertFileUnchanged($result, file_load($result->fid, TRUE));
}
function testExistingError() {
$contents = $this
->randomName(8);
$existing = $this
->createFile(NULL, $contents);
$result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
$this
->assertFalse($result, t('Overwriting a file fails when FILE_EXISTS_ERROR is specified.'));
$this
->assertEqual($contents, file_get_contents($existing->uri), t('Contents of existing file were unchanged.'));
$this
->assertFileHooksCalled(array());
$this
->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
}
}
class FileDownloadTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File download',
'description' => 'Tests for file download/transfer functions.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp('file_test');
}
function testPublicFileTransfer() {
$file = $this
->createFile();
$url = file_create_url($file->uri);
$this
->assertEqual($GLOBALS['base_url'] . '/' . file_directory_path() . '/' . $file->filename, $url, t('Correctly generated a URL for a created file.'));
$this
->drupalHead($url);
$this
->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the created file.'));
$filepath = 'misc/jquery.js';
$url = file_create_url($filepath);
$this
->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, t('Correctly generated a URL for a shipped file.'));
$this
->drupalHead($url);
$this
->assertResponse(200, t('Confirmed that the generated URL is correct by downloading the shipped file.'));
}
function testPrivateFileTransfer() {
$file = $this
->createFile(NULL, NULL, 'private');
$url = file_create_url($file->uri);
file_test_set_return('download', array(
'x-foo' => 'Bar',
));
$this
->drupalHead($url);
$headers = $this
->drupalGetHeaders();
$this
->assertEqual($headers['x-foo'], 'Bar', t('Found header set by file_test module on private download.'));
$this
->assertResponse(200, t('Correctly allowed access to a file when file_test provides headers.'));
file_test_set_return('download', -1);
$this
->drupalHead($url);
$this
->assertResponse(403, t('Correctly denied access to a file when file_test sets the header to -1.'));
$url = file_create_url('private://' . $this
->randomName());
$this
->drupalHead($url);
$this
->assertResponse(404, t('Correctly returned 404 response for a non-existent file.'));
}
}
class FileURLRewritingTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File URL rewriting',
'description' => 'Tests for file URL rewriting.',
'group' => 'File',
);
}
function setUp() {
parent::setUp('file_test');
variable_set('file_test_hook_file_url_alter', TRUE);
}
function testShippedFileURL() {
$filepath = 'misc/jquery.js';
$url = file_create_url($filepath);
$this
->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, t('Correctly generated a URL for a shipped file.'));
$filepath = 'misc/favicon.ico';
$url = file_create_url($filepath);
$this
->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, t('Correctly generated a URL for a shipped file.'));
}
function testPublicCreatedFileURL() {
$file = $this
->createFile();
$url = file_create_url($file->uri);
$this
->assertEqual(FILE_URL_TEST_CDN_2 . '/' . file_directory_path() . '/' . $file->filename, $url, t('Correctly generated a URL for a created file.'));
}
}
class FileNameMungingTest extends FileTestCase {
public static function getInfo() {
return array(
'name' => 'File naming',
'description' => 'Test filename munging and unmunging.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp();
$this->bad_extension = 'php';
$this->name = $this
->randomName() . '.' . $this->bad_extension . '.txt';
}
function testMunging() {
variable_set('allow_insecure_uploads', 0);
$munged_name = file_munge_filename($this->name, '', TRUE);
$messages = drupal_get_messages();
$this
->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array(
'%filename' => $munged_name,
)), $messages['status']), t('Alert properly set when a file is renamed.'));
$this
->assertNotEqual($munged_name, $this->name, t('The new filename (%munged) has been modified from the original (%original)', array(
'%munged' => $munged_name,
'%original' => $this->name,
)));
}
function testMungeIgnoreInsecure() {
variable_set('allow_insecure_uploads', 1);
$munged_name = file_munge_filename($this->name, '');
$this
->assertIdentical($munged_name, $this->name, t('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array(
'%munged' => $munged_name,
'%original' => $this->name,
)));
}
function testMungeIgnoreWhitelisted() {
$munged_name = file_munge_filename($this->name, $this->bad_extension);
$this
->assertIdentical($munged_name, $this->name, t('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array(
'%munged' => $munged_name,
'%original' => $this->name,
)));
}
function testUnMunge() {
$munged_name = file_munge_filename($this->name, '', FALSE);
$unmunged_name = file_unmunge_filename($munged_name);
}
}
class FileMimeTypeTest extends DrupalWebTestCase {
function setUp() {
parent::setUp('file_test');
}
public static function getInfo() {
return array(
'name' => 'File mimetypes',
'description' => 'Test filename mimetype detection.',
'group' => 'File API',
);
}
public function testFileMimeTypeDetection() {
$prefix = 'simpletest://';
$test_case = array(
'test.jar' => 'application/java-archive',
'test.jpeg' => 'image/jpeg',
'test.JPEG' => 'image/jpeg',
'test.jpg' => 'image/jpeg',
'test.jar.jpg' => 'image/jpeg',
'test.jpg.jar' => 'application/java-archive',
'test.pcf.Z' => 'application/x-font',
'pcf.z' => 'application/octet-stream',
'jar' => 'application/octet-stream',
'some.junk' => 'application/octet-stream',
'foo.file_test_1' => 'madeup/file_test_1',
'foo.file_test_2' => 'madeup/file_test_2',
'foo.doc' => 'madeup/doc',
);
foreach ($test_case as $input => $expected) {
$output = file_get_mimetype($prefix . $input);
$this
->assertIdentical($output, $expected, t('Mimetype for %input is %output (expected: %expected).', array(
'%input' => $input,
'%output' => $output,
'%expected' => $expected,
)));
$output = file_get_mimetype($input);
$this
->assertIdentical($output, $expected, t('Mimetype (using default mappings) for %input is %output (expected: %expected).', array(
'%input' => $input,
'%output' => $output,
'%expected' => $expected,
)));
}
$mapping = array(
'mimetypes' => array(
0 => 'application/java-archive',
1 => 'image/jpeg',
),
'extensions' => array(
'jar' => 0,
'jpg' => 1,
),
);
$test_case = array(
'test.jar' => 'application/java-archive',
'test.jpeg' => 'application/octet-stream',
'test.jpg' => 'image/jpeg',
'test.jar.jpg' => 'image/jpeg',
'test.jpg.jar' => 'application/java-archive',
'test.pcf.z' => 'application/octet-stream',
'pcf.z' => 'application/octet-stream',
'jar' => 'application/octet-stream',
'some.junk' => 'application/octet-stream',
'foo.file_test_1' => 'application/octet-stream',
'foo.file_test_2' => 'application/octet-stream',
'foo.doc' => 'application/octet-stream',
);
foreach ($test_case as $input => $expected) {
$output = file_get_mimetype($input, $mapping);
$this
->assertIdentical($output, $expected, t('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array(
'%input' => $input,
'%output' => $output,
'%expected' => $expected,
)));
}
}
}
class StreamWrapperTest extends DrupalWebTestCase {
protected $scheme = 'dummy';
protected $classname = 'DrupalDummyStreamWrapper';
public static function getInfo() {
return array(
'name' => 'Stream wrappers',
'description' => 'Tests stream wrapper functions.',
'group' => 'File API',
);
}
function setUp() {
parent::setUp('file_test');
drupal_static_reset('file_get_stream_wrappers');
}
function tearDown() {
parent::tearDown();
stream_wrapper_unregister($this->scheme);
}
function testGetClassName() {
$this
->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), t('Got correct class name for dummy scheme.'));
$this
->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), t('Got correct class name for public scheme.'));
}
function testGetInstanceByScheme() {
$instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
$this
->assertEqual($this->classname, get_class($instance), t('Got correct class type for dummy scheme.'));
$instance = file_stream_wrapper_get_instance_by_scheme('public');
$this
->assertEqual('DrupalPublicStreamWrapper', get_class($instance), t('Got correct class type for public scheme.'));
}
function testUriFunctions() {
$instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
$this
->assertEqual($this->classname, get_class($instance), t('Got correct class type for dummy URI.'));
$instance = file_stream_wrapper_get_instance_by_uri('public://foo');
$this
->assertEqual('DrupalPublicStreamWrapper', get_class($instance), t('Got correct class type for public URI.'));
$uri = 'public:///' . file_directory_path() . '/foo/bar/';
$uri = file_stream_wrapper_uri_normalize($uri);
$this
->assertEqual('public://foo/bar', $uri, t('Got a properly normalized URI @uri', array(
'@uri' => $uri,
)));
$this
->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', t('Got a valid stream target from public://foo/bar.txt.'));
$this
->assertFalse(file_uri_target('foo/bar.txt'), t('foo/bar.txt is not a valid stream.'));
$this
->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', t('Expected scheme was added.'));
$this
->assertEqual(file_directory_path(), variable_get('file_public_path'), t('Expected default directory path was returned.'));
$this
->assertEqual(file_directory_path('public'), variable_get('file_public_path'), t('Expected public directory path was returned.'));
$this
->assertEqual(file_directory_path('temporary'), conf_path() . '/private/temp', t('Expected temporary directory path was returned.'));
$this
->assertEqual(file_directory_path($this->scheme), variable_get('stream_public_path', 'sites/default/files'), t('Expected dummy directory path was returned.'));
$this
->assertFalse(file_directory_path('non-existent'), t('No directory path returned for invalid scheme.'));
variable_set('file_default_scheme', 'private');
$this
->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', t('Got a valid URI from foo/bar.txt.'));
$this
->assertEqual(file_directory_path(), variable_get('file_private_path'), t('Expected default directory path was returned.'));
$this
->assertEqual(file_directory_path('private'), variable_get('file_private_path'), t('Expected private directory path was returned.'));
}
function testGetValidStreamScheme() {
$this
->assertEqual('foo', file_uri_scheme('foo://pork//chops'), t('Got the correct scheme from foo://asdf'));
$this
->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), t('Got a valid stream scheme from public://asdf'));
$this
->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), t('Did not get a valid stream scheme from foo://asdf'));
}
}