file.test 41.3 KB
Newer Older
webchick's avatar
webchick committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// $Id$

/**
 *  @file
 *  This provides SimpleTests for the core file handling functionality.
 *  These include FileValidateTest and FileSaveTest.
 */

/**
 * Helper validator that returns the $errors parameter.
 */
function file_test_validator($file, $errors) {
  return $errors;
}

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
 * Base class for file tests that adds some additional file specific
 * assertions and helper functions.
 */
class FileTestCase extends DrupalWebTestCase {
  /**
   * Helper function to test the permissions of a file.
   *
   * @param $filepath
   *   String file path.
   * @param $expected_mode
   *   Octal integer like 0664 or 0777.
   * @param $message
   *   Optional message.
   */
  function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
    // Mask out all but the last three octets.
    $actual_mode = fileperms($filepath) & 511;
    if (is_null($message)) {
      if ($actual_mode == $expected_mode) {
        $message = t('File permissions set correctly.');
      }
      else {
        $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);
  }

  /**
   * Create a directory and assert it exists.
   *
   * @param $path
   *   Optional string with a directory path. If none is provided, a random
   *   name in the site's files directory will be used.
   * @return
   *   The path to the directory.
   */
  function createDirectory($path = NULL) {
    // A directory to operate on.
    if (is_null($path)) {
      $path = file_directory_path() . '/' . $this->randomName();
    }
    $this->assertTrue(mkdir($path) && is_dir($path), t('Directory was created successfully.'));
    return $path;
  }

  /**
   * Create a file and save it to the files table and assert that it occurs
   * correctly.
   *
   * @param $filepath
   *   Optional string specifying the file path. If none is provided then a
   *   randomly named file will be created in the site's files directory.
   * @return
   *   File object.
   */
  function createFile($filepath = NULL) {
    if (is_null($filepath)) {
      $filepath = file_directory_path() . '/' . $this->randomName();
    }

79
    file_put_contents($filepath, 'File put contents does not seem to appreciate empty strings so lets put in some data.');
80
81
82
83
84
85
86
87
    $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'));

    $file = new stdClass();
    $file->filepath = $filepath;
    $file->filename = basename($file->filepath);
    $file->filemime = 'text/plain';
    $file->uid = 1;
    $file->timestamp = REQUEST_TIME;
88
89
    $file->filesize = filesize($file->filepath);
    $file->status = FILE_STATUS_TEMPORARY;
90
91
92
93
94
95
    $this->assertNotIdentical(drupal_write_record('files', $file), FALSE, t('The file was added to the database.'));

    return $file;
  }
}

96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/**
 * Base class for file tests that use the file_test module to test uploads and
 * hooks.
 */
class FileHookTestCase extends FileTestCase {
  function setUp() {
    // Install file_test module
    parent::setUp('file_test');
    // Clear out any hook calls.
    file_test_reset();
  }

  /**
   * Assert that a hook_file_* hook was called a certain number of times.
   *
   * @param $hook
   *   String with the hook name, e.g. 'load', 'save', 'insert', etc.
   * @param $expected_count
   *   Optional integer count.
   * @param $message
   *   Optional translated string message.
   */
  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));
      }
      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);
  }
}

webchick's avatar
webchick committed
133
134
135
/**
 *  This will run tests against the file validation functions (file_validate_*).
 */
136
class FileValidatorTest extends DrupalWebTestCase {
webchick's avatar
webchick committed
137
138
  function getInfo() {
    return array(
139
      'name' => t('File validator tests'),
webchick's avatar
webchick committed
140
141
142
143
144
145
146
147
148
149
      'description' => t('Tests the functions used to validate uploaded files.'),
      'group' => t('File'),
    );
  }

  function setUp() {
    parent::setUp();

    $this->image = new stdClass();
    $this->image->filepath = 'misc/druplicon.png';
150
    $this->image->filename = basename($this->image->filepath);
webchick's avatar
webchick committed
151
152
153
154
155
156
157
158
159
160
161
162
163

    $this->non_image = new stdClass();
    $this->non_image->filepath = 'misc/jquery.js';
    $this->non_image->filename = basename($this->non_image->filepath);
  }

  /**
   * Test the file_validate_extensions() function.
   */
  function testFileValidateExtensions() {
    $file = new stdClass();
    $file->filename = 'asdf.txt';
    $errors = file_validate_extensions($file, 'asdf txt pork');
164
    $this->assertEqual(count($errors), 0, t('Valid extension accepted.'), 'File');
webchick's avatar
webchick committed
165
166
167

    $file->filename = 'asdf.txt';
    $errors = file_validate_extensions($file, 'exe png');
168
    $this->assertEqual(count($errors), 1, t('Invalid extension blocked.'), 'File');
webchick's avatar
webchick committed
169
170
171
172
173
174
175
176
  }

  /**
   *  This ensures a specific file is actually an image.
   */
  function testFileValidateIsImage() {
    $this->assertTrue(file_exists($this->image->filepath), t('The image being tested exists.'), 'File');
    $errors = file_validate_is_image($this->image);
177
    $this->assertEqual(count($errors), 0, t('No error reported for our image file.'), 'File');
webchick's avatar
webchick committed
178
179
180

    $this->assertTrue(file_exists($this->non_image->filepath), t('The non-image being tested exists.'), 'File');
    $errors = file_validate_is_image($this->non_image);
181
    $this->assertEqual(count($errors), 1, t('An error reported for our non-image file.'), 'File');
webchick's avatar
webchick committed
182
183
184
185
186
187
188
  }

  /**
   *  This ensures the resolution of a specific file is within bounds.
   *  The image will be resized if it's too large.
   */
  function testFileValidateImageResolution() {
189
    // Non-images.
webchick's avatar
webchick committed
190
191
192
193
194
    $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');

195
    // Minimum size.
webchick's avatar
webchick committed
196
    $errors = file_validate_image_resolution($this->image);
197
    $this->assertEqual(count($errors), 0, t('No errors for an image when there is no minimum or maximum resolution.'), 'File');
webchick's avatar
webchick committed
198
    $errors = file_validate_image_resolution($this->image, 0, '200x1');
199
    $this->assertEqual(count($errors), 1, t("Got an error for an image that wasn't wide enough."), 'File');
webchick's avatar
webchick committed
200
    $errors = file_validate_image_resolution($this->image, 0, '1x200');
201
    $this->assertEqual(count($errors), 1, t("Got an error for an image that wasn't tall enough."), 'File');
webchick's avatar
webchick committed
202
    $errors = file_validate_image_resolution($this->image, 0, '200x200');
203
    $this->assertEqual(count($errors), 1, t('Small images report an error.'), 'File');
webchick's avatar
webchick committed
204

205
    // Maximum size.
webchick's avatar
webchick committed
206
207
208
    if (image_get_toolkit()) {
      // Copy the image so that the original doesn't get resized.
      $temp_dir = file_directory_temp();
209
210
      copy(realpath('misc/druplicon.png'), realpath($temp_dir) . '/druplicon.png');
      $this->image->filepath = $temp_dir . '/druplicon.png';
webchick's avatar
webchick committed
211
212

      $errors = file_validate_image_resolution($this->image, '10x5');
213
      $this->assertEqual(count($errors), 0, t('No errors should be reported when an oversized image can be scaled down.'), 'File');
webchick's avatar
webchick committed
214
215

      $info = image_get_info($this->image->filepath);
216
217
      $this->assertTrue($info['width'] <= 10, t('Image scaled to correct width.'), 'File');
      $this->assertTrue($info['height'] <= 5, t('Image scaled to correct height.'), 'File');
webchick's avatar
webchick committed
218

219
      unlink(realpath($temp_dir . '/druplicon.png'));
webchick's avatar
webchick committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
    }
    else {
      // TODO: should check that the error is returned if no toolkit is available.
      $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');
    }
  }

  /**
   *  This will ensure the filename length is valid.
   */
  function testFileValidateNameLength() {
    // Create a new file object.
    $file = new stdClass();

    // Add a filename with an allowed length and test it.
    $file->filename = str_repeat('x', 255);
    $this->assertEqual(strlen($file->filename), 255);
    $errors = file_validate_name_length($file);
    $this->assertEqual(count($errors), 0, t('No errors reported for 255 length filename.'), 'File');

    // Add a filename with a length too long and test it.
    $file->filename = str_repeat('x', 256);
    $errors = file_validate_name_length($file);
    $this->assertEqual(count($errors), 1, t('An error reported for 256 length filename.'), 'File');

    // Add a filename with an empty string and test it.
    $file->filename = '';
    $errors = file_validate_name_length($file);
    $this->assertEqual(count($errors), 1, t('An error reported for 0 length filename.'), 'File');
  }


  /**
   * Test file_validate_size().
   */
  function testFileValidateSize() {
    global $user;
    $original_user = $user;
259
    drupal_save_session(FALSE);
webchick's avatar
webchick committed
260

261
    // Run these test as uid = 1.
webchick's avatar
webchick committed
262
263
264
265
266
    $user = user_load(array('uid' => 1));

    $file = new stdClass();
    $file->filesize = 999999;
    $errors = file_validate_size($file, 1, 1);
267
    $this->assertEqual(count($errors), 0, t('No size limits enforced on uid=1.'), 'File');
webchick's avatar
webchick committed
268

269
    // Run these tests as a regular user.
webchick's avatar
webchick committed
270
271
    $user = $this->drupalCreateUser();

272
    // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
webchick's avatar
webchick committed
273
274
275
    $file = new stdClass();
    $file->filesize = 1000;
    $errors = file_validate_size($file, 0, 0);
276
    $this->assertEqual(count($errors), 0, t('No limits means no errors.'), 'File');
webchick's avatar
webchick committed
277
    $errors = file_validate_size($file, 1, 0);
278
    $this->assertEqual(count($errors), 1, t('Error for the file being over the limit.'), 'File');
webchick's avatar
webchick committed
279
    $errors = file_validate_size($file, 0, 1);
280
    $this->assertEqual(count($errors), 1, t('Error for the user being over their limit.'), 'File');
webchick's avatar
webchick committed
281
    $errors = file_validate_size($file, 1, 1);
282
    $this->assertEqual(count($errors), 2, t('Errors for both the file and their limit.'), 'File');
webchick's avatar
webchick committed
283
284

    $user = $original_user;
285
    drupal_save_session(TRUE);
webchick's avatar
webchick committed
286
287
288
  }
}

289
290


webchick's avatar
webchick committed
291
/**
292
 *  Tests the file_unmanaged_save_data() function.
webchick's avatar
webchick committed
293
 */
294
class FileUnmanagedSaveDataTest extends FileTestCase {
webchick's avatar
webchick committed
295
296
  function getInfo() {
    return array(
297
298
      'name' => t('Unmanaged file save data'),
      'description' => t('Tests the unmanaged file save data function.'),
webchick's avatar
webchick committed
299
300
301
302
      'group' => t('File'),
    );
  }

303
  /**
304
   * Test the file_unmanaged_save_data() function.
305
   */
webchick's avatar
webchick committed
306
307
308
  function testFileSaveData() {
    $contents = $this->randomName(8);

309
    // No filename.
310
    $filepath = file_unmanaged_save_data($contents);
311
312
313
    $this->assertTrue($filepath, t('Unnamed file saved correctly.'));
    $this->assertEqual(file_directory_path(), dirname($filepath), t("File was placed in Drupal's files directory."));
    $this->assertEqual($contents, file_get_contents(realpath($filepath)), t('Contents of the file are correct.'));
webchick's avatar
webchick committed
314

315
    // Provide a filename.
316
    $filepath = file_unmanaged_save_data($contents, 'asdf.txt', FILE_EXISTS_REPLACE);
317
    $this->assertTrue($filepath, t('Unnamed file saved correctly.'));
webchick's avatar
webchick committed
318
    $this->assertEqual(file_directory_path(), dirname($filepath), t("File was placed in Drupal's files directory."));
319
320
321
    $this->assertEqual('asdf.txt', basename($filepath), t('File was named correctly.'));
    $this->assertEqual($contents, file_get_contents(realpath($filepath)), t('Contents of the file are correct.'));
    $this->assertFilePermissions($filepath, 0664);
webchick's avatar
webchick committed
322
323
324
325
  }
}

/**
326
 * Test the file_save_upload() function.
webchick's avatar
webchick committed
327
 */
328
class FileSaveUploadTest extends FileHookTestCase {
webchick's avatar
webchick committed
329
330
  function getInfo() {
    return array(
331
332
      'name' => t('File uploading'),
      'description' => t('Tests the file uploading functions.'),
webchick's avatar
webchick committed
333
334
335
336
      'group' => t('File'),
    );
  }

337
338
339
340
341
342
343
344
345
346
347
348
349
350
  /**
   * Test the file_save_upload() function.
   */
  function testFileSaveUpload() {
    $max_fid_before = db_result(db_query('SELECT MAX(fid) AS fid FROM {files}'));
    $upload_user = $this->drupalCreateUser(array('access content'));
    $this->drupalLogin($upload_user);

    $image = current($this->drupalGetTestFiles('image'));
    $this->assertTrue(is_file($image->filename), t("The file we're going to upload exists."));
    $edit = array('files[file_test_upload]' => realpath($image->filename));
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
    $this->assertResponse(200, t('Received a 200 response for posted test file.'));

351
352
353
354
    // We can't easily check that the hooks were called but since
    // file_save_upload() calles file_save() we can rely on file_save()'s
    // test to catch problems invoking the hooks.

355
356
    $max_fid_after = db_result(db_query('SELECT MAX(fid) AS fid FROM {files}'));
    $this->assertTrue($max_fid_after > $max_fid_before, t('A new file was created.'));
357
    $this->assertTrue(file_load($max_fid_after), t('Loaded the file.'));
358
359
360
361
362
363
364
365
366
367
368
369
370
  }
}

/**
 * Directory related tests.
 */
class FileDirectoryTest extends FileTestCase {
  function getInfo() {
    return array(
      'name' => t('File paths and directories'),
      'description' => t('Tests operations dealing with directories.'),
      'group' => t('File'),
    );
webchick's avatar
webchick committed
371
372
373
  }

  /**
374
   * Test the file_directory_path() function.
webchick's avatar
webchick committed
375
376
   */
  function testFileCheckDirectory() {
377
378
379
380
381
    // A directory to operate on.
    $directory = file_directory_path() . '/' . $this->randomName();
    $this->assertFalse(is_dir($directory), t('Directory does not exist prior to testing.'));

    // Non-existent directory.
webchick's avatar
webchick committed
382
    $form_element = $this->randomName();
383
    $this->assertFalse(file_check_directory($directory, 0, $form_element), t('Error reported for non-existing directory.'), 'File');
webchick's avatar
webchick committed
384

385
    // Check that an error was set for the form element above.
webchick's avatar
webchick committed
386
    $errors = form_get_errors();
387
    $this->assertEqual($errors[$form_element], t('The directory %directory does not exist.', array('%directory' => $directory)), t('Properly generated an error for the passed form element.'), 'File');
webchick's avatar
webchick committed
388

389
390
    // Make a directory.
    $this->assertTrue(file_check_directory($directory, FILE_CREATE_DIRECTORY), t('No error reported when creating a new directory.'), 'File');
webchick's avatar
webchick committed
391

392
393
    // Make sure directory actually exists.
    $this->assertTrue(is_dir($directory), t('Directory actually exists.'), 'File');
webchick's avatar
webchick committed
394

395
396
    // Make directory read only.
    @chmod($directory, 0444);
webchick's avatar
webchick committed
397
    $form_element = $this->randomName();
398
    $this->assertFalse(file_check_directory($directory, 0, $form_element), t('Error reported for a non-writeable directory.'), 'File');
webchick's avatar
webchick committed
399

400
    // Check if form error was set.
webchick's avatar
webchick committed
401
    $errors = form_get_errors();
402
    $this->assertEqual($errors[$form_element], t('The directory %directory is not writable', array('%directory' => $directory)), t('Properly generated an error for the passed form element.'), 'File');
webchick's avatar
webchick committed
403

404
405
    // Test directory permission modification.
    $this->assertTrue(file_check_directory($directory, FILE_MODIFY_PERMISSIONS), t('No error reported when making directory writeable.'), 'File');
webchick's avatar
webchick committed
406

407
408
    // Verify directory actually is writeable.
    $this->assertTrue(is_writeable($directory), t('Directory is writeable.'), 'File');
webchick's avatar
webchick committed
409

410
    // Remove .htaccess file to then test that it gets re-created.
webchick's avatar
webchick committed
411
    @unlink(file_directory_path() .'/.htaccess');
412
413
    $directory = file_directory_path();
    file_check_directory($directory);
webchick's avatar
webchick committed
414
415
    $this->assertTrue(is_file(file_directory_path() . '/.htaccess'), t('Successfully created the .htaccess file in the files directory.'), 'File');

416
    // Verify contents of .htaccess file.
webchick's avatar
webchick committed
417
418
419
420
421
422
423
424
    $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');
  }

  /**
   * Check file_directory_path() and file_directory_temp().
   */
  function testFileDirectoryPath() {
425
    // Directory path.
webchick's avatar
webchick committed
426
    $path = variable_get('file_directory_path', conf_path() . '/files');
427
    $this->assertEqual($path, file_directory_path(), t('Properly returns the stored file directory path.'), 'File');
webchick's avatar
webchick committed
428
429
430
431
432
433
  }

  /**
   * Check file_directory_path() and file_directory_temp().
   */
  function testFileDirectoryTemp() {
434
    // Temporary directory handling.
webchick's avatar
webchick committed
435
436
    variable_set('file_directory_temp', NULL);
    $temp = file_directory_temp();
437
    $this->assertTrue(!is_null($temp), t('Properly set and retrieved temp directory %directory.', array('%directory' => $temp)), 'File');
webchick's avatar
webchick committed
438
439
440
  }

  /**
441
442
   * This tests that a file is actually in the specified directory, to prevent
   * exploits.
webchick's avatar
webchick committed
443
444
445
446
447
   */
  function testFileCheckLocation() {
    $source = 'misc/xyz.txt';
    $directory = 'misc';
    $result = file_check_location($source, $directory);
448
    $this->assertTrue($result, t('Non-existent file validates when checked for location in existing directory.'), 'File');
webchick's avatar
webchick committed
449
450
451
452

    $source = 'fake/xyz.txt';
    $directory = 'fake';
    $result = file_check_location($source, $directory);
453
    $this->assertTrue($result, t('Non-existent file validates when checked for location in non-existing directory.'), 'File');
webchick's avatar
webchick committed
454
455
456
457

    $source = 'misc/../install.php';
    $directory = 'misc';
    $result = file_check_location($source, $directory);
458
    $this->assertFalse($result, t('Existing file fails validation when it exists outside the directory path, using a /../ exploit.'), 'File');
webchick's avatar
webchick committed
459
460
461
462

    $source = 'misc/druplicon.png';
    $directory = 'misc';
    $result = file_check_location($source, $directory);
463
    $this->assertTrue($result, t('Existing file passes validation when checked for location in directory path, and filepath contains a subfolder of the checked path.'), 'File');
webchick's avatar
webchick committed
464
465

    $result = file_check_location($source, $directory);
466
    $this->assertTrue($result, t('Existing file passes validation, returning the source when checked for location in directory.'), 'File');
webchick's avatar
webchick committed
467
468
469
470
  }


  /**
471
472
   * This will take a directory and path, and find a valid filepath that is not
   * taken by another file.
webchick's avatar
webchick committed
473
474
   */
  function testFileCreateNewFilepath() {
475
476
    // First we test against an imaginary file that does not exist in a
    // directory.
webchick's avatar
webchick committed
477
478
479
480
    $basename = 'xyz.txt';
    $directory = 'misc';
    $original = $directory .'/'. $basename;
    $path = file_create_filename($basename, $directory);
481
    $this->assertEqual($path, $original, t('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
webchick's avatar
webchick committed
482

483
    // Then we test against a file that already exists within that directory.
webchick's avatar
webchick committed
484
485
486
487
    $basename = 'druplicon.png';
    $original = $directory .'/'. $basename;
    $expected = $directory .'/druplicon_0.png';
    $path = file_create_filename($basename, $directory);
488
489
490
    $this->assertEqual($path, $expected, t('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');

    // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
webchick's avatar
webchick committed
491
492
493
494
495
  }

  /**
   * This will test the filepath for a destination based on passed flags and
   * whether or not the file exists.
496
497
498
499
500
501
502
503
   *
   * If a file exists, file_destination($destination, $replace) will either
   * return:
   * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
   * - a new filepath if FILE_EXISTS_RENAME
   * - an error (returning FALSE) if FILE_EXISTS_ERROR.
   * If the file doesn't currently exist, then it will simply return the
   * filepath.
webchick's avatar
webchick committed
504
505
506
507
508
   */
  function testFileDestination() {
    // First test for non-existent file.
    $destination = 'misc/xyz.txt';
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
509
    $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.'), 'File');
webchick's avatar
webchick committed
510
    $path = file_destination($destination, FILE_EXISTS_RENAME);
511
    $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_RENAME.'), 'File');
webchick's avatar
webchick committed
512
    $path = file_destination($destination, FILE_EXISTS_ERROR);
513
    $this->assertEqual($path, $destination, t('Non-existing filepath destination is correct with FILE_EXISTS_ERROR.'), 'File');
webchick's avatar
webchick committed
514
515
516

    $destination = 'misc/druplicon.png';
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
517
    $this->assertEqual($path, $destination, t('Existing filepath destination remains the same with FILE_EXISTS_REPLACE.'), 'File');
webchick's avatar
webchick committed
518
    $path = file_destination($destination, FILE_EXISTS_RENAME);
519
    $this->assertNotEqual($path, $destination, t('A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.'), 'File');
webchick's avatar
webchick committed
520
    $path = file_destination($destination, FILE_EXISTS_ERROR);
521
    $this->assertEqual($path, FALSE, t('An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.'), 'File');
webchick's avatar
webchick committed
522
523
524
525
  }
}


526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/**
 * Tests the file_scan_directory() function.
 */
class FileScanDirectoryTest extends FileTestCase {
  function getInfo() {
    return array(
      'name' => t('File scan directory'),
      'description' => t('Tests the file_scan_directory() function.'),
      'group' => t('File'),
    );
  }

  /**
   * Check that the no-mask parameter is honored.
   */
  function testNoMask() {
542
    $path = $this->originalFileDirectory . '/simpletest';
543
544
545
546
547
548
549
550
551
552
553
554

    // Grab a listing of all the JS files.
    $all_files = file_scan_directory($path, '/javascript*/');
    $this->assertEqual(2, count($all_files), t('Found two, expected javascript files.'));

    // Now use the nomast parameter to filter out the .script file.
    $filtered_files = file_scan_directory($path, '/javascript*/', '/.script$/');
    $this->assertEqual(1, count($filtered_files), t('Filtered correctly.'));
  }
}


webchick's avatar
webchick committed
555
/**
556
 * Deletion related tests.
webchick's avatar
webchick committed
557
 */
558
class FileUnmanagedDeleteTest extends FileTestCase {
webchick's avatar
webchick committed
559
560
  function getInfo() {
    return array(
561
562
      'name' => t('Unmanaged file delete'),
      'description' => t('Tests the unmanaged file delete function.'),
webchick's avatar
webchick committed
563
564
565
566
567
      'group' => t('File'),
    );
  }

  /**
568
   * Delete a normal file.
webchick's avatar
webchick committed
569
   */
570
  function testNormal() {
webchick's avatar
webchick committed
571
    // Create a file for testing
572
573
    $file = $this->createFile();

webchick's avatar
webchick committed
574
    // Delete a regular file
575
    $this->assertTrue(file_unmanaged_delete($file->filepath), t('Deleted worked.'));
576
    $this->assertFalse(file_exists($file->filepath), t('Test file has actually been deleted.'));
webchick's avatar
webchick committed
577
578
  }

579
580
581
582
  /**
   * Try deleting a missing file.
   */
  function testMissing() {
webchick's avatar
webchick committed
583
    // Try to delete a non-existing file
584
    $this->assertTrue(file_unmanaged_delete(file_directory_path() . '/' . $this->randomName()), t('Returns true when deleting a non-existant file.'));
webchick's avatar
webchick committed
585
586
  }

587
588
589
590
591
  /**
   * Try deleting a directory.
   */
  function testDirectory() {
    // A directory to operate on.
592
    $directory = $this->createDirectory();
593

webchick's avatar
webchick committed
594
    // Try to delete a directory
595
596
    $this->assertFalse(file_unmanaged_delete($directory), t('Could not delete the delete directory.'));
    $this->assertTrue(file_exists($directory), t('Directory has not been deleted.'));
597
598
599
600
601
  }
}


/**
602
 * Unmanaged move related tests.
603
 */
604
class FileUnmanagedMoveTest extends FileTestCase {
605
606
  function getInfo() {
    return array(
607
608
      'name' => t('Unmanaged file moving'),
      'description' => t('Tests the unmanaged file move function.'),
609
610
      'group' => t('File'),
    );
webchick's avatar
webchick committed
611
612
  }

613
614
615
616
617
618
619
  /**
   * Move a normal file.
   */
  function testNormal() {
    // Create a file for testing
    $file = $this->createFile();

webchick's avatar
webchick committed
620
621
    // Moving to a new name.
    $desired_filepath = file_directory_path() . '/' . $this->randomName();
622
    $new_filepath = file_unmanaged_move($file->filepath, $desired_filepath, FILE_EXISTS_ERROR);
623
624
625
626
627
    $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->filepath), t('No file remains at the old location.'));
    $this->assertFilePermissions($new_filepath, 0664);
webchick's avatar
webchick committed
628
629
630

    // Moving with rename.
    $desired_filepath = file_directory_path() . '/' . $this->randomName();
631
632
    $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.'));
633
    $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
634
635
636
637
638
    $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, 0664);
webchick's avatar
webchick committed
639
640
641
642

    // TODO: test moving to a directory (rather than full directory/file path)
  }

643
644
645
646
647
  /**
   * Try to move a missing file.
   */
  function testMissing() {
    // Move non-existant file.
648
    $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
649
    $this->assertFalse($new_filepath, t('Moving a missing file fails.'));
webchick's avatar
webchick committed
650
651
  }

652
653
654
655
656
657
658
  /**
   * Try to move a file onto itself.
   */
  function testOverwriteSelf() {
    // Create a file for testing.
    $file = $this->createFile();

webchick's avatar
webchick committed
659
    // Move the file onto itself without renaming shouldn't make changes.
660
    $new_filepath = file_unmanaged_move($file->filepath, $file->filepath, FILE_EXISTS_REPLACE);
661
662
    $this->assertFalse($new_filepath, t('Moving onto itself without renaming fails.'));
    $this->assertTrue(file_exists($file->filepath), t('File exists after moving onto itself.'));
webchick's avatar
webchick committed
663
664

    // Move the file onto itself with renaming will result in a new filename.
665
    $new_filepath = file_unmanaged_move($file->filepath, $file->filepath, FILE_EXISTS_RENAME);
666
667
668
669
670
    $this->assertTrue($new_filepath, t('Moving onto itself with renaming works.'));
    $this->assertFalse(file_exists($file->filepath), t('Original file has been removed.'));
    $this->assertTrue(file_exists($new_filepath), t('File exists after moving onto itself.'));
  }
}
webchick's avatar
webchick committed
671

672
673

/**
674
 * Unmanaged copy related tests.
675
 */
676
class FileUnmanagedCopyTest extends FileTestCase {
677
678
  function getInfo() {
    return array(
679
680
      'name' => t('Unmanaged file copying'),
      'description' => t('Tests the unmanaged file copy function.'),
681
682
      'group' => t('File'),
    );
webchick's avatar
webchick committed
683
684
  }

685
686
687
688
689
  /**
   * Copy a normal file.
   */
  function testNormal() {
    // Create a file for testing
690
    $file = $this->createFile();
691

webchick's avatar
webchick committed
692
693
    // Copying to a new name.
    $desired_filepath = file_directory_path() . '/' . $this->randomName();
694
    $new_filepath = file_unmanaged_copy($file->filepath, $desired_filepath, FILE_EXISTS_ERROR);
695
696
    $this->assertTrue($new_filepath, t('Copy was successful.'));
    $this->assertEqual($new_filepath, $desired_filepath, t('Returned expected filepath.'));
697
    $this->assertTrue(file_exists($file->filepath), t('Original file remains.'));
698
699
    $this->assertTrue(file_exists($new_filepath), t('New file exists.'));
    $this->assertFilePermissions($new_filepath, 0664);
webchick's avatar
webchick committed
700
701
702

    // Copying with rename.
    $desired_filepath = file_directory_path() . '/' . $this->randomName();
703
    $this->assertTrue(file_put_contents($desired_filepath, ' '), t('Created a file so a rename will have to happen.'));
704
    $newer_filepath = file_unmanaged_copy($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
705
706
    $this->assertTrue($newer_filepath, t('Copy was successful.'));
    $this->assertNotEqual($newer_filepath, $desired_filepath, t('Returned expected filepath.'));
707
    $this->assertTrue(file_exists($file->filepath), t('Original file remains.'));
708
709
    $this->assertTrue(file_exists($new_filepath), t('New file exists.'));
    $this->assertFilePermissions($new_filepath, 0664);
webchick's avatar
webchick committed
710
711
712
713

    // TODO: test copying to a directory (rather than full directory/file path)
  }

714
715
716
717
  /**
   * Copy a non-existant file.
   */
  function testNonExistant() {
webchick's avatar
webchick committed
718
719
720
    // Copy non-existant file
    $desired_filepath = $this->randomName();
    $this->assertFalse(file_exists($desired_filepath), t("Randomly named file doesn't exists."));
721
    $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
722
    $this->assertFalse($new_filepath, t('Copying a missing file fails.'));
webchick's avatar
webchick committed
723
724
  }

725
726
727
728
729
  /**
   * Copy a file onto itself.
   */
  function testOverwriteSelf() {
    // Create a file for testing
730
    $file = $this->createFile();
731

webchick's avatar
webchick committed
732
    // Copy the file onto itself with renaming works.
733
    $new_filepath = file_unmanaged_copy($file->filepath, $file->filepath, FILE_EXISTS_RENAME);
734
    $this->assertTrue($new_filepath, t('Copying onto itself with renaming works.'));
735
736
    $this->assertNotEqual($new_filepath, $file->filepath, t('Copied file has a new name.'));
    $this->assertTrue(file_exists($file->filepath), t('Original file exists after copying onto itself.'));
737
    $this->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
webchick's avatar
webchick committed
738
739

    // Copy the file onto itself without renaming fails.
740
    $new_filepath = file_unmanaged_copy($file->filepath, $file->filepath, FILE_EXISTS_ERROR);
741
    $this->assertFalse($new_filepath, t('Copying onto itself without renaming fails.'));
742
    $this->assertTrue(file_exists($file->filepath), t('File exists after copying onto itself.'));
webchick's avatar
webchick committed
743
744

    // Copy the file into same directory without renaming fails.
745
    $new_filepath = file_unmanaged_copy($file->filepath, dirname($file->filepath), FILE_EXISTS_ERROR);
746
    $this->assertFalse($new_filepath, t('Copying onto itself fails.'));
747
    $this->assertTrue(file_exists($file->filepath), t('File exists after copying onto itself.'));
webchick's avatar
webchick committed
748
749

    // Copy the file into same directory with renaming works.
750
    $new_filepath = file_unmanaged_copy($file->filepath, dirname($file->filepath), FILE_EXISTS_RENAME);
751
    $this->assertTrue($new_filepath, t('Copying into same directory works.'));
752
753
    $this->assertNotEqual($new_filepath, $file->filepath, t('Copied file has a new name.'));
    $this->assertTrue(file_exists($file->filepath), t('Original file exists after copying onto itself.'));
754
    $this->assertTrue(file_exists($new_filepath), t('Copied file exists after copying onto itself.'));
webchick's avatar
webchick committed
755
756
757
  }
}

758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963


/**
 * Deletion related tests.
 */
class FileDeleteTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File delete'),
      'description' => t('Tests the file delete function.'),
      'group' => t('File'),
    );
  }

  /**
   * Try deleting a normal file (as opposed to a directory, symlink, etc).
   */
  function testNormal() {
    $file = $this->createFile();

    // Check that deletion removes the file and database record.
    $this->assertTrue(is_file($file->filepath), t("File exists."));
    $this->assertIdentical(file_delete($file), TRUE, t("Delete worked."));
    $this->assertFileHookCalled('references');
    $this->assertFileHookCalled('delete');
    $this->assertFalse(file_exists($file->filepath), t("Test file has actually been deleted."));
    $this->assertFalse(file_load(array('filepath' => $file->filepath)), t("File was removed from the database."));

    // TODO: implement hook_file_references() in file_test.module and report a
    // file in use and test the $force parameter.
  }
}


/**
 * Move related tests
 */
class FileMoveTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File moving'),
      'description' => t('Tests the file move function.'),
      'group' => t('File'),
    );
  }

  /**
   * Move a normal file.
   */
  function testNormal() {
    $file = $this->createFile();
    $desired_filepath = file_directory_path() . '/' . $this->randomName();

    $file = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
    $this->assertTrue($file, t("File moved sucessfully."));
    $this->assertFileHookCalled('move');
    $this->assertFileHookCalled('update');
    $this->assertEqual($file->fid, $file->fid, t("File id $file->fid is unchanged after move."));

    $loaded_file = file_load($file->fid, TRUE);
    $this->assertTrue($loaded_file, t("File can be loaded from the database."));
    $this->assertEqual($file->filename, $loaded_file->filename, t("File name was updated correctly in the database."));
    $this->assertEqual($file->filepath, $loaded_file->filepath, t("File path was updated correctly in the database."));
  }
}


/**
 * Copy related tests.
 */
class FileCopyTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File copying'),
      'description' => t('Tests the file copy function.'),
      'group' => t('File'),
    );
  }

  /**
   * Test copying a normal file.
   */
  function testNormal() {
    $source_file = $this->createFile();
    $desired_filepath = file_directory_path() . '/' . $this->randomName();

    $file = file_copy(clone $source_file, $desired_filepath, FILE_EXISTS_ERROR);
    $this->assertTrue($file, t("File copied sucessfully."));
    $this->assertFileHookCalled('copy');
    $this->assertFileHookCalled('insert');
    $this->assertNotEqual($source_file->fid, $file->fid, t("A new file id was created."));
    $this->assertNotEqual($source_file->filepath, $file->filepath, t("A new filepath was created."));
    $this->assertEqual($file->filepath, $desired_filepath, t('The copied file object has the desired filepath.'));
    $this->assertTrue(file_exists($source_file->filepath), t('The original file still exists.'));
    $this->assertTrue(file_exists($file->filepath), t('The copied file exists.'));

    // Check that the changes were actually saved to the database.
    $loaded_file = file_load($file->fid, TRUE);
    $this->assertTrue($loaded_file, t("File can be loaded from the database."));
    $this->assertEqual($file->filename, $loaded_file->filename, t("File name was updated correctly in the database."));
    $this->assertEqual($file->filepath, $loaded_file->filepath, t("File path was updated correctly in the database."));
  }
}


/**
 * Tests the file_load() function.
 */
class FileLoadTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File loading'),
      'description' => t('Tests the file_load() function.'),
      'group' => t('File'),
    );
  }

  /**
   * Try to load a non-existant file by fid.
   */
  function testLoadMissingFid() {
    $this->assertFalse(file_load(-1), t("Try to load an invalid fid fails."));
    $this->assertFileHookCalled('load', 0);
  }

  /**
   * Try to load a non-existant file by filepath.
   */
  function testLoadMissingFilepath() {
    $this->assertFalse(file_load(array('filepath' => 'misc/druplicon.png')), t("Try to load a file that doesn't exist in the database fails."));
    $this->assertFileHookCalled('load', 0);
  }

  /**
   * Try to load a non-existant file by status.
   */
  function testLoadInvalidStatus() {
    $this->assertFalse(file_load(array('status' => -99)), t("Trying to load a file with an invalid status fails."));
    $this->assertFileHookCalled('load', 0);
  }

  /**
   * This will test lading file data from the database.
   */
  function testFileLoad() {
    // Create a new file object.
    $file = array(
      'uid' => 1,
      'filename' => 'druplicon.png',
      'filepath' => 'misc/druplicon.png',
      'filemime' => 'image/png',
      'timestamp' => 1,
      'status' => FILE_STATUS_PERMANENT,
    );
    $file = file_save($file);

    // Load by path.
    file_test_reset();
    $by_path_file = file_load(array('filepath' => $file->filepath));
    $this->assertFileHookCalled('load');
    $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');

    // Load by fid.
    file_test_reset();
    $by_fid_file = file_load($file->fid);
    $this->assertFileHookCalled('load', 0);
    $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->filepath, $file->filepath, t("Loading by fid got the correct filepath."), 'File');

    // Load again by fid but use the reset param to reload.
    file_test_reset();
    $by_fid_file = file_load($file->fid, TRUE);
    $this->assertFileHookCalled('load');
    $this->assertEqual($by_fid_file->filepath, $file->filepath, t("Loading by fid got the correct filepath."), 'File');
  }
}
/**
 * Tests the file_save() function.
 */
class FileSaveTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File saving'),
      'description' => t('Tests the file_save() function.'),
      'group' => t('File'),
    );
  }

  function testFileSave() {
    // Create a new file object.
    $file = array(
      'uid' => 1,
      'filename' => 'druplicon.png',
      'filepath' => 'misc/druplicon.png',
      'filemime' => 'image/png',
      'timestamp' => 1,
      'status' => FILE_STATUS_PERMANENT,
    );
    $file = (object) $file;

    // Save it, inserting a new record.
    $saved_file = file_save($file);
    $this->assertFileHookCalled('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');
964
965
966
    $loaded_file = db_query('SELECT * FROM {files} 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."));
967
968
969
970
971
    $this->assertEqual($saved_file->filesize, filesize($file->filepath), 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();
972
    $saved_file->status = 7;
973
974
975
976
    $resaved_file = file_save($saved_file);
    $this->assertFileHookCalled('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');
977
978
979
    $loaded_file = db_query('SELECT * FROM {files} 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."));
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
  }
}


/**
 * Tests the file_validate() function..
 */
class FileValidateTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File validate'),
      'description' => t('Tests the file_validate() function.'),
      'group' => t('File'),
    );
  }

  /**
   * Test that the validators passed into are checked.
   */
  function testCallerValidation() {
    $file = $this->createFile();

    // Empty validators.
    $this->assertEqual(file_validate($file, array()), array(), t('Validating an empty array works succesfully.'));
    $this->assertFileHookCalled('validate', 1);

    // Use the file_test.module's test validator to ensure that passing tests
    // return correctly.
    file_test_reset();
1009
    file_test_set_return('validate', array());
1010
1011
1012
1013
1014
1015
    $passing = array('file_test_validator' => array(array()));
    $this->assertEqual(file_validate($file, $passing), array(), t('Validating passes.'));
    $this->assertFileHookCalled('validate', 1);

    // Now test for failures in validators passed in and by hook_validate.
    file_test_reset();
1016
    file_test_set_return('validate', array('Epic fail'));
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
    $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->assertFileHookCalled('validate', 1);
  }
}

/**
 *  Tests the file_save_data() function.
 */
class FileSaveDataTest extends FileHookTestCase {
  function getInfo() {
    return array(
      'name' => t('File save data'),
      'description' => t('Tests the file save data function.'),
      'group' => t('File'),
    );
  }

  /**
   * Test the file_save_data() function.
   */
  function testFileSaveData() {
    $contents = $this->randomName(8);

    // No filename.
    $file = file_save_data($contents);
    $this->assertTrue($file, t("Unnamed file saved correctly."));
    $this->assertEqual(file_directory_path(), dirname($file->filepath), t("File was placed in Drupal's files directory."));
    $this->assertEqual($contents, file_get_contents(realpath($file->filepath)), t("Contents of the file are correct."));
    $this->assertEqual($file->filemime, 'application/octet-stream', t("A MIME type was set."));
    $this->assertEqual($file->status, FILE_STATUS_PERMANENT, t("The file's status was set to permanent."));

    // Try loading the file.
    $loaded_file = file_load($file->fid);
    $this->assertTrue($loaded_file, t("File loaded from database."));

    // Provide a filename.
    $file = file_save_data($contents, 'asdf.txt', FILE_EXISTS_REPLACE);
    $this->assertTrue($file, t("Unnamed file saved correctly."));
    $this->assertEqual(file_directory_path(), dirname($file->filepath), t("File was placed in Drupal's files directory."));
    $this->assertEqual('asdf.txt', basename($file->filepath), t("File was named correctly."));
    $this->assertEqual($contents, file_get_contents(realpath($file->filepath)), t("Contents of the file are correct."));

    // Check the overwrite error.
    $file = file_save_data($contents, 'asdf.txt', FILE_EXISTS_ERROR);
    $this->assertFalse($file, t("Overwriting a file fails when FILE_EXISTS_ERROR is specified."));
  }
}