Projet

Général

Profil

Paste
Télécharger (110 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / tests / file.test @ b4adf10d

1
<?php
2

    
3
/**
4
 *  @file
5
 *  This provides SimpleTests for the core file handling functionality.
6
 *  These include FileValidateTest and FileSaveTest.
7
 */
8

    
9
/**
10
 * Helper validator that returns the $errors parameter.
11
 */
12
function file_test_validator($file, $errors) {
13
  return $errors;
14
}
15

    
16
/**
17
 * Helper function for testing file_scan_directory().
18
 *
19
 * Each time the function is called the file is stored in a static variable.
20
 * When the function is called with no $filepath parameter, the results are
21
 * returned.
22
 *
23
 * @param $filepath
24
 *   File path
25
 * @return
26
 *   If $filepath is NULL, an array of all previous $filepath parameters
27
 */
28
function file_test_file_scan_callback($filepath = NULL) {
29
  $files = &drupal_static(__FUNCTION__, array());
30
  if (isset($filepath)) {
31
    $files[] = $filepath;
32
  }
33
  else {
34
    return $files;
35
  }
36
}
37

    
38
/**
39
 * Reset static variables used by file_test_file_scan_callback().
40
 */
41
function file_test_file_scan_callback_reset() {
42
  drupal_static_reset('file_test_file_scan_callback');
43
}
44

    
45
/**
46
 * Base class for file tests that adds some additional file specific
47
 * assertions and helper functions.
48
 */
49
class FileTestCase extends DrupalWebTestCase {
50
  /**
51
   * Check that two files have the same values for all fields other than the
52
   * timestamp.
53
   *
54
   * @param $before
55
   *   File object to compare.
56
   * @param $after
57
   *   File object to compare.
58
   */
59
  function assertFileUnchanged($before, $after) {
60
    $this->assertEqual($before->fid, $after->fid, format_string('File id is the same: %file1 == %file2.', array('%file1' => $before->fid, '%file2' => $after->fid)), 'File unchanged');
61
    $this->assertEqual($before->uid, $after->uid, format_string('File owner is the same: %file1 == %file2.', array('%file1' => $before->uid, '%file2' => $after->uid)), 'File unchanged');
62
    $this->assertEqual($before->filename, $after->filename, format_string('File name is the same: %file1 == %file2.', array('%file1' => $before->filename, '%file2' => $after->filename)), 'File unchanged');
63
    $this->assertEqual($before->uri, $after->uri, format_string('File path is the same: %file1 == %file2.', array('%file1' => $before->uri, '%file2' => $after->uri)), 'File unchanged');
64
    $this->assertEqual($before->filemime, $after->filemime, format_string('File MIME type is the same: %file1 == %file2.', array('%file1' => $before->filemime, '%file2' => $after->filemime)), 'File unchanged');
65
    $this->assertEqual($before->filesize, $after->filesize, format_string('File size is the same: %file1 == %file2.', array('%file1' => $before->filesize, '%file2' => $after->filesize)), 'File unchanged');
66
    $this->assertEqual($before->status, $after->status, format_string('File status is the same: %file1 == %file2.', array('%file1' => $before->status, '%file2' => $after->status)), 'File unchanged');
67
  }
68

    
69
  /**
70
   * Check that two files are not the same by comparing the fid and filepath.
71
   *
72
   * @param $file1
73
   *   File object to compare.
74
   * @param $file2
75
   *   File object to compare.
76
   */
77
  function assertDifferentFile($file1, $file2) {
78
    $this->assertNotEqual($file1->fid, $file2->fid, format_string('Files have different ids: %file1 != %file2.', array('%file1' => $file1->fid, '%file2' => $file2->fid)), 'Different file');
79
    $this->assertNotEqual($file1->uri, $file2->uri, format_string('Files have different paths: %file1 != %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Different file');
80
  }
81

    
82
  /**
83
   * Check that two files are the same by comparing the fid and filepath.
84
   *
85
   * @param $file1
86
   *   File object to compare.
87
   * @param $file2
88
   *   File object to compare.
89
   */
90
  function assertSameFile($file1, $file2) {
91
    $this->assertEqual($file1->fid, $file2->fid, format_string('Files have the same ids: %file1 == %file2.', array('%file1' => $file1->fid, '%file2-fid' => $file2->fid)), 'Same file');
92
    $this->assertEqual($file1->uri, $file2->uri, format_string('Files have the same path: %file1 == %file2.', array('%file1' => $file1->uri, '%file2' => $file2->uri)), 'Same file');
93
  }
94

    
95
  /**
96
   * Helper function to test the permissions of a file.
97
   *
98
   * @param $filepath
99
   *   String file path.
100
   * @param $expected_mode
101
   *   Octal integer like 0664 or 0777.
102
   * @param $message
103
   *   Optional message.
104
   */
105
  function assertFilePermissions($filepath, $expected_mode, $message = NULL) {
106
    // Clear out PHP's file stat cache to be sure we see the current value.
107
    clearstatcache();
108

    
109
    // Mask out all but the last three octets.
110
    $actual_mode = fileperms($filepath) & 0777;
111

    
112
    // PHP on Windows has limited support for file permissions. Usually each of
113
    // "user", "group" and "other" use one octal digit (3 bits) to represent the
114
    // read/write/execute bits. On Windows, chmod() ignores the "group" and
115
    // "other" bits, and fileperms() returns the "user" bits in all three
116
    // positions. $expected_mode is updated to reflect this.
117
    if (substr(PHP_OS, 0, 3) == 'WIN') {
118
      // Reset the "group" and "other" bits.
119
      $expected_mode = $expected_mode & 0700;
120
      // Shift the "user" bits to the "group" and "other" positions also.
121
      $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
122
    }
123

    
124
    if (!isset($message)) {
125
      $message = t('Expected file permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
126
    }
127
    $this->assertEqual($actual_mode, $expected_mode, $message);
128
  }
129

    
130
  /**
131
   * Helper function to test the permissions of a directory.
132
   *
133
   * @param $directory
134
   *   String directory path.
135
   * @param $expected_mode
136
   *   Octal integer like 0664 or 0777.
137
   * @param $message
138
   *   Optional message.
139
   */
140
  function assertDirectoryPermissions($directory, $expected_mode, $message = NULL) {
141
    // Clear out PHP's file stat cache to be sure we see the current value.
142
    clearstatcache();
143

    
144
    // Mask out all but the last three octets.
145
    $actual_mode = fileperms($directory) & 0777;
146

    
147
    // PHP on Windows has limited support for file permissions. Usually each of
148
    // "user", "group" and "other" use one octal digit (3 bits) to represent the
149
    // read/write/execute bits. On Windows, chmod() ignores the "group" and
150
    // "other" bits, and fileperms() returns the "user" bits in all three
151
    // positions. $expected_mode is updated to reflect this.
152
    if (substr(PHP_OS, 0, 3) == 'WIN') {
153
      // Reset the "group" and "other" bits.
154
      $expected_mode = $expected_mode & 0700;
155
      // Shift the "user" bits to the "group" and "other" positions also.
156
      $expected_mode = $expected_mode | $expected_mode >> 3 | $expected_mode >> 6;
157
    }
158

    
159
    if (!isset($message)) {
160
      $message = t('Expected directory permission to be %expected, actually were %actual.', array('%actual' => decoct($actual_mode), '%expected' => decoct($expected_mode)));
161
    }
162
    $this->assertEqual($actual_mode, $expected_mode, $message);
163
  }
164

    
165
  /**
166
   * Create a directory and assert it exists.
167
   *
168
   * @param $path
169
   *   Optional string with a directory path. If none is provided, a random
170
   *   name in the site's files directory will be used.
171
   * @return
172
   *   The path to the directory.
173
   */
174
  function createDirectory($path = NULL) {
175
    // A directory to operate on.
176
    if (!isset($path)) {
177
      $path = file_default_scheme() . '://' . $this->randomName();
178
    }
179
    $this->assertTrue(drupal_mkdir($path) && is_dir($path), 'Directory was created successfully.');
180
    return $path;
181
  }
182

    
183
  /**
184
   * Create a file and save it to the files table and assert that it occurs
185
   * correctly.
186
   *
187
   * @param $filepath
188
   *   Optional string specifying the file path. If none is provided then a
189
   *   randomly named file will be created in the site's files directory.
190
   * @param $contents
191
   *   Optional contents to save into the file. If a NULL value is provided an
192
   *   arbitrary string will be used.
193
   * @param $scheme
194
   *   Optional string indicating the stream scheme to use. Drupal core includes
195
   *   public, private, and temporary. The public wrapper is the default.
196
   * @return
197
   *   File object.
198
   */
199
  function createFile($filepath = NULL, $contents = NULL, $scheme = NULL) {
200
    if (!isset($filepath)) {
201
      // Prefix with non-latin characters to ensure that all file-related
202
      // tests work with international filenames.
203
      $filepath = 'Файл для тестирования ' . $this->randomName();
204
    }
205
    if (!isset($scheme)) {
206
      $scheme = file_default_scheme();
207
    }
208
    $filepath = $scheme . '://' . $filepath;
209

    
210
    if (!isset($contents)) {
211
      $contents = "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.";
212
    }
213

    
214
    file_put_contents($filepath, $contents);
215
    $this->assertTrue(is_file($filepath), 'The test file exists on the disk.', 'Create test file');
216

    
217
    $file = new stdClass();
218
    $file->uri = $filepath;
219
    $file->filename = drupal_basename($file->uri);
220
    $file->filemime = 'text/plain';
221
    $file->uid = 1;
222
    $file->timestamp = REQUEST_TIME;
223
    $file->filesize = filesize($file->uri);
224
    $file->status = 0;
225
    // Write the record directly rather than calling file_save() so we don't
226
    // invoke the hooks.
227
    $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, 'The file was added to the database.', 'Create test file');
228

    
229
    return $file;
230
  }
231
}
232

    
233
/**
234
 * Base class for file tests that use the file_test module to test uploads and
235
 * hooks.
236
 */
237
class FileHookTestCase extends FileTestCase {
238
  function setUp() {
239
    // Install file_test module
240
    parent::setUp('file_test');
241
    // Clear out any hook calls.
242
    file_test_reset();
243
  }
244

    
245
  /**
246
   * Assert that all of the specified hook_file_* hooks were called once, other
247
   * values result in failure.
248
   *
249
   * @param $expected
250
   *   Array with string containing with the hook name, e.g. 'load', 'save',
251
   *   'insert', etc.
252
   */
253
  function assertFileHooksCalled($expected) {
254
    // Determine which hooks were called.
255
    $actual = array_keys(array_filter(file_test_get_all_calls()));
256

    
257
    // Determine if there were any expected that were not called.
258
    $uncalled = array_diff($expected, $actual);
259
    if (count($uncalled)) {
260
      $this->assertTrue(FALSE, format_string('Expected hooks %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
261
    }
262
    else {
263
      $this->assertTrue(TRUE, format_string('All the expected hooks were called: %expected', array('%expected' => empty($expected) ? t('(none)') : implode(', ', $expected))));
264
    }
265

    
266
    // Determine if there were any unexpected calls.
267
    $unexpected = array_diff($actual, $expected);
268
    if (count($unexpected)) {
269
      $this->assertTrue(FALSE, format_string('Unexpected hooks were called: %unexpected.', array('%unexpected' => empty($unexpected) ? t('(none)') : implode(', ', $unexpected))));
270
    }
271
    else {
272
      $this->assertTrue(TRUE, 'No unexpected hooks were called.');
273
    }
274
  }
275

    
276
  /**
277
   * Assert that a hook_file_* hook was called a certain number of times.
278
   *
279
   * @param $hook
280
   *   String with the hook name, e.g. 'load', 'save', 'insert', etc.
281
   * @param $expected_count
282
   *   Optional integer count.
283
   * @param $message
284
   *   Optional translated string message.
285
   */
286
  function assertFileHookCalled($hook, $expected_count = 1, $message = NULL) {
287
    $actual_count = count(file_test_get_calls($hook));
288

    
289
    if (!isset($message)) {
290
      if ($actual_count == $expected_count) {
291
        $message = format_string('hook_file_@name was called correctly.', array('@name' => $hook));
292
      }
293
      elseif ($expected_count == 0) {
294
        $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));
295
      }
296
      else {
297
        $message = format_string('hook_file_@name was expected to be called %expected times but was called %actual times.', array('@name' => $hook, '%expected' => $expected_count, '%actual' => $actual_count));
298
      }
299
    }
300
    $this->assertEqual($actual_count, $expected_count, $message);
301
  }
302
}
303

    
304

    
305
/**
306
 *  This will run tests against the file_space_used() function.
307
 */
308
class FileSpaceUsedTest extends FileTestCase {
309
  public static function getInfo() {
310
    return array(
311
      'name' => 'File space used tests',
312
      'description' => 'Tests the file_space_used() function.',
313
      'group' => 'File API',
314
    );
315
  }
316

    
317
  function setUp() {
318
    parent::setUp();
319

    
320
    // Create records for a couple of users with different sizes.
321
    $file = array('uid' => 2, 'uri' => 'public://example1.txt', 'filesize' => 50, 'status' => FILE_STATUS_PERMANENT);
322
    drupal_write_record('file_managed', $file);
323
    $file = array('uid' => 2, 'uri' => 'public://example2.txt', 'filesize' => 20, 'status' => FILE_STATUS_PERMANENT);
324
    drupal_write_record('file_managed', $file);
325
    $file = array('uid' => 3, 'uri' => 'public://example3.txt', 'filesize' => 100, 'status' => FILE_STATUS_PERMANENT);
326
    drupal_write_record('file_managed', $file);
327
    $file = array('uid' => 3, 'uri' => 'public://example4.txt', 'filesize' => 200, 'status' => FILE_STATUS_PERMANENT);
328
    drupal_write_record('file_managed', $file);
329

    
330
    // Now create some non-permanent files.
331
    $file = array('uid' => 2, 'uri' => 'public://example5.txt', 'filesize' => 1, 'status' => 0);
332
    drupal_write_record('file_managed', $file);
333
    $file = array('uid' => 3, 'uri' => 'public://example6.txt', 'filesize' => 3, 'status' => 0);
334
    drupal_write_record('file_managed', $file);
335
  }
336

    
337
  /**
338
   * Test different users with the default status.
339
   */
340
  function testFileSpaceUsed() {
341
    // Test different users with default status.
342
    $this->assertEqual(file_space_used(2), 70);
343
    $this->assertEqual(file_space_used(3), 300);
344
    $this->assertEqual(file_space_used(), 370);
345

    
346
    // Test the status fields
347
    $this->assertEqual(file_space_used(NULL, 0), 4);
348
    $this->assertEqual(file_space_used(NULL, FILE_STATUS_PERMANENT), 370);
349

    
350
    // Test both the user and status.
351
    $this->assertEqual(file_space_used(1, 0), 0);
352
    $this->assertEqual(file_space_used(1, FILE_STATUS_PERMANENT), 0);
353
    $this->assertEqual(file_space_used(2, 0), 1);
354
    $this->assertEqual(file_space_used(2, FILE_STATUS_PERMANENT), 70);
355
    $this->assertEqual(file_space_used(3, 0), 3);
356
    $this->assertEqual(file_space_used(3, FILE_STATUS_PERMANENT), 300);
357
  }
358
}
359

    
360
/**
361
 *  This will run tests against the file validation functions (file_validate_*).
362
 */
363
class FileValidatorTest extends DrupalWebTestCase {
364
  public static function getInfo() {
365
    return array(
366
      'name' => 'File validator tests',
367
      'description' => 'Tests the functions used to validate uploaded files.',
368
      'group' => 'File API',
369
    );
370
  }
371

    
372
  function setUp() {
373
    parent::setUp();
374

    
375
    $this->image = new stdClass();
376
    $this->image->uri = 'misc/druplicon.png';
377
    $this->image->filename = drupal_basename($this->image->uri);
378

    
379
    $this->non_image = new stdClass();
380
    $this->non_image->uri = 'misc/jquery.js';
381
    $this->non_image->filename = drupal_basename($this->non_image->uri);
382
  }
383

    
384
  /**
385
   * Test the file_validate_extensions() function.
386
   */
387
  function testFileValidateExtensions() {
388
    $file = new stdClass();
389
    $file->filename = 'asdf.txt';
390
    $errors = file_validate_extensions($file, 'asdf txt pork');
391
    $this->assertEqual(count($errors), 0, 'Valid extension accepted.', 'File');
392

    
393
    $file->filename = 'asdf.txt';
394
    $errors = file_validate_extensions($file, 'exe png');
395
    $this->assertEqual(count($errors), 1, 'Invalid extension blocked.', 'File');
396
  }
397

    
398
  /**
399
   *  This ensures a specific file is actually an image.
400
   */
401
  function testFileValidateIsImage() {
402
    $this->assertTrue(file_exists($this->image->uri), 'The image being tested exists.', 'File');
403
    $errors = file_validate_is_image($this->image);
404
    $this->assertEqual(count($errors), 0, 'No error reported for our image file.', 'File');
405

    
406
    $this->assertTrue(file_exists($this->non_image->uri), 'The non-image being tested exists.', 'File');
407
    $errors = file_validate_is_image($this->non_image);
408
    $this->assertEqual(count($errors), 1, 'An error reported for our non-image file.', 'File');
409
  }
410

    
411
  /**
412
   *  This ensures the resolution of a specific file is within bounds.
413
   *  The image will be resized if it's too large.
414
   */
415
  function testFileValidateImageResolution() {
416
    // Non-images.
417
    $errors = file_validate_image_resolution($this->non_image);
418
    $this->assertEqual(count($errors), 0, 'Should not get any errors for a non-image file.', 'File');
419
    $errors = file_validate_image_resolution($this->non_image, '50x50', '100x100');
420
    $this->assertEqual(count($errors), 0, 'Do not check the resolution on non files.', 'File');
421

    
422
    // Minimum size.
423
    $errors = file_validate_image_resolution($this->image);
424
    $this->assertEqual(count($errors), 0, 'No errors for an image when there is no minimum or maximum resolution.', 'File');
425
    $errors = file_validate_image_resolution($this->image, 0, '200x1');
426
    $this->assertEqual(count($errors), 1, 'Got an error for an image that was not wide enough.', 'File');
427
    $errors = file_validate_image_resolution($this->image, 0, '1x200');
428
    $this->assertEqual(count($errors), 1, 'Got an error for an image that was not tall enough.', 'File');
429
    $errors = file_validate_image_resolution($this->image, 0, '200x200');
430
    $this->assertEqual(count($errors), 1, 'Small images report an error.', 'File');
431

    
432
    // Maximum size.
433
    if (image_get_toolkit()) {
434
      // Copy the image so that the original doesn't get resized.
435
      copy('misc/druplicon.png', 'temporary://druplicon.png');
436
      $this->image->uri = 'temporary://druplicon.png';
437

    
438
      $errors = file_validate_image_resolution($this->image, '10x5');
439
      $this->assertEqual(count($errors), 0, 'No errors should be reported when an oversized image can be scaled down.', 'File');
440

    
441
      $info = image_get_info($this->image->uri);
442
      $this->assertTrue($info['width'] <= 10, 'Image scaled to correct width.', 'File');
443
      $this->assertTrue($info['height'] <= 5, 'Image scaled to correct height.', 'File');
444

    
445
      drupal_unlink('temporary://druplicon.png');
446
    }
447
    else {
448
      // TODO: should check that the error is returned if no toolkit is available.
449
      $errors = file_validate_image_resolution($this->image, '5x10');
450
      $this->assertEqual(count($errors), 1, 'Oversize images that cannot be scaled get an error.', 'File');
451
    }
452
  }
453

    
454
  /**
455
   *  This will ensure the filename length is valid.
456
   */
457
  function testFileValidateNameLength() {
458
    // Create a new file object.
459
    $file = new stdClass();
460

    
461
    // Add a filename with an allowed length and test it.
462
    $file->filename = str_repeat('x', 240);
463
    $this->assertEqual(strlen($file->filename), 240);
464
    $errors = file_validate_name_length($file);
465
    $this->assertEqual(count($errors), 0, 'No errors reported for 240 length filename.', 'File');
466

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

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

    
478

    
479
  /**
480
   * Test file_validate_size().
481
   */
482
  function testFileValidateSize() {
483
    global $user;
484
    $original_user = $user;
485
    drupal_save_session(FALSE);
486

    
487
    // Run these tests as a regular user.
488
    $user = $this->drupalCreateUser();
489

    
490
    // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
491
    $file = new stdClass();
492
    $file->filesize = 1000;
493
    $errors = file_validate_size($file, 0, 0);
494
    $this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
495
    $errors = file_validate_size($file, 1, 0);
496
    $this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
497
    $errors = file_validate_size($file, 0, 1);
498
    $this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
499
    $errors = file_validate_size($file, 1, 1);
500
    $this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
501

    
502
    $user = $original_user;
503
    drupal_save_session(TRUE);
504
  }
505
}
506

    
507

    
508

    
509
/**
510
 *  Tests the file_unmanaged_save_data() function.
511
 */
512
class FileUnmanagedSaveDataTest extends FileTestCase {
513
  public static function getInfo() {
514
    return array(
515
      'name' => 'Unmanaged file save data',
516
      'description' => 'Tests the unmanaged file save data function.',
517
      'group' => 'File API',
518
    );
519
  }
520

    
521
  /**
522
   * Test the file_unmanaged_save_data() function.
523
   */
524
  function testFileSaveData() {
525
    $contents = $this->randomName(8);
526

    
527
    // No filename.
528
    $filepath = file_unmanaged_save_data($contents);
529
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
530
    $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
531
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
532

    
533
    // Provide a filename.
534
    $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
535
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
536
    $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
537
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
538
    $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
539
  }
540
}
541

    
542
/**
543
 *  Tests the file_unmanaged_save_data() function on remote filesystems.
544
 */
545
class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
546
  public static function getInfo() {
547
    $info = parent::getInfo();
548
    $info['group'] = 'File API (remote)';
549
    return $info;
550
  }
551

    
552
  function setUp() {
553
    parent::setUp('file_test');
554
    variable_set('file_default_scheme', 'dummy-remote');
555
  }
556
}
557

    
558
/**
559
 * Test the file_save_upload() function.
560
 */
561
class FileSaveUploadTest extends FileHookTestCase {
562
  /**
563
   * An image file path for uploading.
564
   */
565
  protected $image;
566

    
567
  /**
568
   * A PHP file path for upload security testing.
569
   */
570
  protected $phpfile;
571

    
572
  /**
573
   * The largest file id when the test starts.
574
   */
575
  protected $maxFidBefore;
576

    
577
  public static function getInfo() {
578
    return array(
579
      'name' => 'File uploading',
580
      'description' => 'Tests the file uploading functions.',
581
      'group' => 'File API',
582
    );
583
  }
584

    
585
  function setUp() {
586
    parent::setUp();
587
    $account = $this->drupalCreateUser(array('access content'));
588
    $this->drupalLogin($account);
589

    
590
    $image_files = $this->drupalGetTestFiles('image');
591
    $this->image = current($image_files);
592

    
593
    list(, $this->image_extension) = explode('.', $this->image->filename);
594
    $this->assertTrue(is_file($this->image->uri), "The image file we're going to upload exists.");
595

    
596
    $this->phpfile = current($this->drupalGetTestFiles('php'));
597
    $this->assertTrue(is_file($this->phpfile->uri), "The PHP file we're going to upload exists.");
598

    
599
    $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
600

    
601
    // Upload with replace to guarantee there's something there.
602
    $edit = array(
603
      'file_test_replace' => FILE_EXISTS_REPLACE,
604
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
605
    );
606
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
607
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
608
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
609

    
610
    // Check that the correct hooks were called then clean out the hook
611
    // counters.
612
    $this->assertFileHooksCalled(array('validate', 'insert'));
613
    file_test_reset();
614
  }
615

    
616
  /**
617
   * Test the file_save_upload() function.
618
   */
619
  function testNormal() {
620
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
621
    $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
622
    $file1 = file_load($max_fid_after);
623
    $this->assertTrue($file1, 'Loaded the file.');
624
    // MIME type of the uploaded image may be either image/jpeg or image/png.
625
    $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
626

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

    
630
    // Upload a second file.
631
    $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
632
    $image2 = current($this->drupalGetTestFiles('image'));
633
    $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
634
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
635
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
636
    $this->assertRaw(t('You WIN!'));
637
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
638

    
639
    // Check that the correct hooks were called.
640
    $this->assertFileHooksCalled(array('validate', 'insert'));
641

    
642
    $file2 = file_load($max_fid_after);
643
    $this->assertTrue($file2);
644
    // MIME type of the uploaded image may be either image/jpeg or image/png.
645
    $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
646

    
647
    // Load both files using file_load_multiple().
648
    $files = file_load_multiple(array($file1->fid, $file2->fid));
649
    $this->assertTrue(isset($files[$file1->fid]), 'File was loaded successfully');
650
    $this->assertTrue(isset($files[$file2->fid]), 'File was loaded successfully');
651

    
652
    // Upload a third file to a subdirectory.
653
    $image3 = current($this->drupalGetTestFiles('image'));
654
    $image3_realpath = drupal_realpath($image3->uri);
655
    $dir = $this->randomName();
656
    $edit = array(
657
      'files[file_test_upload]' => $image3_realpath,
658
      'file_subdir' => $dir,
659
    );
660
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
661
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
662
    $this->assertRaw(t('You WIN!'));
663
    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
664

    
665
    // Check that file_load_multiple() with no arguments returns FALSE.
666
    $this->assertFalse(file_load_multiple(), 'No files were loaded.');
667
  }
668

    
669
  /**
670
   * Test extension handling.
671
   */
672
  function testHandleExtension() {
673
    // The file being tested is a .gif which is in the default safe list
674
    // of extensions to allow when the extension validator isn't used. This is
675
    // implicitly tested at the testNormal() test. Here we tell
676
    // file_save_upload() to only allow ".foo".
677
    $extensions = 'foo';
678
    $edit = array(
679
      'file_test_replace' => FILE_EXISTS_REPLACE,
680
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
681
      'extensions' => $extensions,
682
    );
683

    
684
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
685
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
686
    $message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
687
    $this->assertRaw($message, 'Cannot upload a disallowed extension');
688
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
689

    
690
    // Check that the correct hooks were called.
691
    $this->assertFileHooksCalled(array('validate'));
692

    
693
    // Reset the hook counters.
694
    file_test_reset();
695

    
696
    $extensions = 'foo ' . $this->image_extension;
697
    // Now tell file_save_upload() to allow the extension of our test image.
698
    $edit = array(
699
      'file_test_replace' => FILE_EXISTS_REPLACE,
700
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
701
      'extensions' => $extensions,
702
    );
703

    
704
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
705
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
706
    $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
707
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
708

    
709
    // Check that the correct hooks were called.
710
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
711

    
712
    // Reset the hook counters.
713
    file_test_reset();
714

    
715
    // Now tell file_save_upload() to allow any extension.
716
    $edit = array(
717
      'file_test_replace' => FILE_EXISTS_REPLACE,
718
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
719
      'allow_all_extensions' => TRUE,
720
    );
721
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
722
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
723
    $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
724
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
725

    
726
    // Check that the correct hooks were called.
727
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
728
  }
729

    
730
  /**
731
   * Test dangerous file handling.
732
   */
733
  function testHandleDangerousFile() {
734
    // Allow the .php extension and make sure it gets renamed to .txt for
735
    // safety. Also check to make sure its MIME type was changed.
736
    $edit = array(
737
      'file_test_replace' => FILE_EXISTS_REPLACE,
738
      'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
739
      'is_image_file' => FALSE,
740
      'extensions' => 'php',
741
    );
742

    
743
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
744
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
745
    $message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
746
    $this->assertRaw($message, 'Dangerous file was renamed.');
747
    $this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
748
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
749

    
750
    // Check that the correct hooks were called.
751
    $this->assertFileHooksCalled(array('validate', 'insert'));
752

    
753
    // Ensure dangerous files are not renamed when insecure uploads is TRUE.
754
    // Turn on insecure uploads.
755
    variable_set('allow_insecure_uploads', 1);
756
    // Reset the hook counters.
757
    file_test_reset();
758

    
759
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
760
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
761
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
762
    $this->assertRaw(t('File name is !filename', array('!filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
763
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
764

    
765
    // Check that the correct hooks were called.
766
    $this->assertFileHooksCalled(array('validate', 'insert'));
767

    
768
    // Turn off insecure uploads.
769
    variable_set('allow_insecure_uploads', 0);
770
  }
771

    
772
  /**
773
   * Test file munge handling.
774
   */
775
  function testHandleFileMunge() {
776
    // Ensure insecure uploads are disabled for this test.
777
    variable_set('allow_insecure_uploads', 0);
778
    $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
779

    
780
    // Reset the hook counters to get rid of the 'move' we just called.
781
    file_test_reset();
782

    
783
    $extensions = $this->image_extension;
784
    $edit = array(
785
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
786
      'extensions' => $extensions,
787
    );
788

    
789
    $munged_filename = $this->image->filename;
790
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
791
    $munged_filename .= '_.' . $this->image_extension;
792

    
793
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
794
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
795
    $this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
796
    $this->assertRaw(t('File name is !filename', array('!filename' => $munged_filename)), 'File was successfully munged.');
797
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
798

    
799
    // Check that the correct hooks were called.
800
    $this->assertFileHooksCalled(array('validate', 'insert'));
801

    
802
    // Ensure we don't munge files if we're allowing any extension.
803
    // Reset the hook counters.
804
    file_test_reset();
805

    
806
    $edit = array(
807
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
808
      'allow_all_extensions' => TRUE,
809
    );
810

    
811
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
812
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
813
    $this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
814
    $this->assertRaw(t('File name is !filename', array('!filename' => $this->image->filename)), 'File was not munged when allowing any extension.');
815
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
816

    
817
    // Check that the correct hooks were called.
818
    $this->assertFileHooksCalled(array('validate', 'insert'));
819
  }
820

    
821
  /**
822
   * Test renaming when uploading over a file that already exists.
823
   */
824
  function testExistingRename() {
825
    $edit = array(
826
      'file_test_replace' => FILE_EXISTS_RENAME,
827
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
828
    );
829
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
830
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
831
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
832

    
833
    // Check that the correct hooks were called.
834
    $this->assertFileHooksCalled(array('validate', 'insert'));
835
  }
836

    
837
  /**
838
   * Test replacement when uploading over a file that already exists.
839
   */
840
  function testExistingReplace() {
841
    $edit = array(
842
      'file_test_replace' => FILE_EXISTS_REPLACE,
843
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
844
    );
845
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
846
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
847
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
848

    
849
    // Check that the correct hooks were called.
850
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
851
  }
852

    
853
  /**
854
   * Test for failure when uploading over a file that already exists.
855
   */
856
  function testExistingError() {
857
    $edit = array(
858
      'file_test_replace' => FILE_EXISTS_ERROR,
859
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
860
    );
861
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
862
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
863
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
864

    
865
    // Check that the no hooks were called while failing.
866
    $this->assertFileHooksCalled(array());
867
  }
868

    
869
  /**
870
   * Test for no failures when not uploading a file.
871
   */
872
  function testNoUpload() {
873
    $this->drupalPost('file-test/upload', array(), t('Submit'));
874
    $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
875
  }
876
}
877

    
878
/**
879
 * Test the file_save_upload() function on remote filesystems.
880
 */
881
class RemoteFileSaveUploadTest extends FileSaveUploadTest {
882
  public static function getInfo() {
883
    $info = parent::getInfo();
884
    $info['group'] = 'File API (remote)';
885
    return $info;
886
  }
887

    
888
  function setUp() {
889
    parent::setUp('file_test');
890
    variable_set('file_default_scheme', 'dummy-remote');
891
  }
892
}
893

    
894
/**
895
 * Directory related tests.
896
 */
897
class FileDirectoryTest extends FileTestCase {
898
  public static function getInfo() {
899
    return array(
900
      'name' => 'File paths and directories',
901
      'description' => 'Tests operations dealing with directories.',
902
      'group' => 'File API',
903
    );
904
  }
905

    
906
  /**
907
   * Test directory handling functions.
908
   */
909
  function testFileCheckDirectoryHandling() {
910
    // A directory to operate on.
911
    $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
912
    $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.');
913

    
914
    // Non-existent directory.
915
    $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File');
916

    
917
    // Make a directory.
918
    $this->assertTrue(file_prepare_directory($directory, FILE_CREATE_DIRECTORY), 'No error reported when creating a new directory.', 'File');
919

    
920
    // Make sure directory actually exists.
921
    $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File');
922

    
923
    if (substr(PHP_OS, 0, 3) != 'WIN') {
924
      // PHP on Windows doesn't support any kind of useful read-only mode for
925
      // directories. When executing a chmod() on a directory, PHP only sets the
926
      // read-only flag, which doesn't prevent files to actually be written
927
      // in the directory on any recent version of Windows.
928

    
929
      // Make directory read only.
930
      @drupal_chmod($directory, 0444);
931
      $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
932

    
933
      // Test directory permission modification.
934
      $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File');
935
    }
936

    
937
    // Test that the directory has the correct permissions.
938
    $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
939

    
940
    // Remove .htaccess file to then test that it gets re-created.
941
    @drupal_unlink(file_default_scheme() . '://.htaccess');
942
    $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File');
943
    file_ensure_htaccess();
944
    $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File');
945
    // Verify contents of .htaccess file.
946
    $file = file_get_contents(file_default_scheme() . '://.htaccess');
947
    $this->assertEqual($file, file_htaccess_lines(FALSE), 'The .htaccess file contains the proper content.', 'File');
948
  }
949

    
950
  /**
951
   * This will take a directory and path, and find a valid filepath that is not
952
   * taken by another file.
953
   */
954
  function testFileCreateNewFilepath() {
955
    // First we test against an imaginary file that does not exist in a
956
    // directory.
957
    $basename = 'xyz.txt';
958
    $directory = 'misc';
959
    $original = $directory . '/' . $basename;
960
    $path = file_create_filename($basename, $directory);
961
    $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
962

    
963
    // Then we test against a file that already exists within that directory.
964
    $basename = 'druplicon.png';
965
    $original = $directory . '/' . $basename;
966
    $expected = $directory . '/druplicon_0.png';
967
    $path = file_create_filename($basename, $directory);
968
    $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
969

    
970
    // @TODO: Finally we copy a file into a directory several times, to ensure a properly iterating filename suffix.
971
  }
972

    
973
  /**
974
   * This will test the filepath for a destination based on passed flags and
975
   * whether or not the file exists.
976
   *
977
   * If a file exists, file_destination($destination, $replace) will either
978
   * return:
979
   * - the existing filepath, if $replace is FILE_EXISTS_REPLACE
980
   * - a new filepath if FILE_EXISTS_RENAME
981
   * - an error (returning FALSE) if FILE_EXISTS_ERROR.
982
   * If the file doesn't currently exist, then it will simply return the
983
   * filepath.
984
   */
985
  function testFileDestination() {
986
    // First test for non-existent file.
987
    $destination = 'misc/xyz.txt';
988
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
989
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_REPLACE.', 'File');
990
    $path = file_destination($destination, FILE_EXISTS_RENAME);
991
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_RENAME.', 'File');
992
    $path = file_destination($destination, FILE_EXISTS_ERROR);
993
    $this->assertEqual($path, $destination, 'Non-existing filepath destination is correct with FILE_EXISTS_ERROR.', 'File');
994

    
995
    $destination = 'misc/druplicon.png';
996
    $path = file_destination($destination, FILE_EXISTS_REPLACE);
997
    $this->assertEqual($path, $destination, 'Existing filepath destination remains the same with FILE_EXISTS_REPLACE.', 'File');
998
    $path = file_destination($destination, FILE_EXISTS_RENAME);
999
    $this->assertNotEqual($path, $destination, 'A new filepath destination is created when filepath destination already exists with FILE_EXISTS_RENAME.', 'File');
1000
    $path = file_destination($destination, FILE_EXISTS_ERROR);
1001
    $this->assertEqual($path, FALSE, 'An error is returned when filepath destination already exists with FILE_EXISTS_ERROR.', 'File');
1002
  }
1003

    
1004
  /**
1005
   * Ensure that the file_directory_temp() function always returns a value.
1006
   */
1007
  function testFileDirectoryTemp() {
1008
    // Start with an empty variable to ensure we have a clean slate.
1009
    variable_set('file_temporary_path', '');
1010
    $tmp_directory = file_directory_temp();
1011
    $this->assertEqual(empty($tmp_directory), FALSE, 'file_directory_temp() returned a non-empty value.');
1012
    $setting = variable_get('file_temporary_path', '');
1013
    $this->assertEqual($setting, $tmp_directory, "The 'file_temporary_path' variable has the same value that file_directory_temp() returned.");
1014
  }
1015
}
1016

    
1017
/**
1018
 * Directory related tests.
1019
 */
1020
class RemoteFileDirectoryTest extends FileDirectoryTest {
1021
  public static function getInfo() {
1022
    $info = parent::getInfo();
1023
    $info['group'] = 'File API (remote)';
1024
    return $info;
1025
  }
1026

    
1027
  function setUp() {
1028
    parent::setUp('file_test');
1029
    variable_set('file_default_scheme', 'dummy-remote');
1030
  }
1031
}
1032

    
1033
/**
1034
 * Tests the file_scan_directory() function.
1035
 */
1036
class FileScanDirectoryTest extends FileTestCase {
1037
  public static function getInfo() {
1038
    return array(
1039
      'name' => 'File scan directory',
1040
      'description' => 'Tests the file_scan_directory() function.',
1041
      'group' => 'File API',
1042
    );
1043
  }
1044

    
1045
  function setUp() {
1046
    parent::setUp();
1047
    $this->path = drupal_get_path('module', 'simpletest') . '/files';
1048
  }
1049

    
1050
  /**
1051
   * Check the format of the returned values.
1052
   */
1053
  function testReturn() {
1054
    // Grab a listing of all the JavaSscript files and check that they're
1055
    // passed to the callback.
1056
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1057
    ksort($all_files);
1058
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1059

    
1060
    // Check the first file.
1061
    $file = reset($all_files);
1062
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.');
1063
    $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.');
1064
    $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly');
1065
    $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.');
1066

    
1067
    // Check the second file.
1068
    $file = next($all_files);
1069
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.');
1070
    $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.');
1071
    $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly');
1072
    $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.');
1073
  }
1074

    
1075
  /**
1076
   * Check that the callback function is called correctly.
1077
   */
1078
  function testOptionCallback() {
1079
    // When nothing is matched nothing should be passed to the callback.
1080
    $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
1081
    $this->assertEqual(0, count($all_files), 'No files were found.');
1082
    $results = file_test_file_scan_callback();
1083
    file_test_file_scan_callback_reset();
1084
    $this->assertEqual(0, count($results), 'No files were passed to the callback.');
1085

    
1086
    // Grab a listing of all the JavaSscript files and check that they're
1087
    // passed to the callback.
1088
    $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
1089
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1090
    $results = file_test_file_scan_callback();
1091
    file_test_file_scan_callback_reset();
1092
    $this->assertEqual(2, count($results), 'Files were passed to the callback.');
1093
  }
1094

    
1095
  /**
1096
   * Check that the no-mask parameter is honored.
1097
   */
1098
  function testOptionNoMask() {
1099
    // Grab a listing of all the JavaSscript files.
1100
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1101
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1102

    
1103
    // Now use the nomast parameter to filter out the .script file.
1104
    $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
1105
    $this->assertEqual(1, count($filtered_files), 'Filtered correctly.');
1106
  }
1107

    
1108
  /**
1109
   * Check that key parameter sets the return value's key.
1110
   */
1111
  function testOptionKey() {
1112
    // "filename", for the path starting with $dir.
1113
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1114
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
1115
    sort($actual);
1116
    $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.');
1117

    
1118
    // "basename", for the basename of the file.
1119
    $expected = array('javascript-1.txt', 'javascript-2.script');
1120
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
1121
    sort($actual);
1122
    $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.');
1123

    
1124
    // "name" for the name of the file without an extension.
1125
    $expected = array('javascript-1', 'javascript-2');
1126
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
1127
    sort($actual);
1128
    $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.');
1129

    
1130
    // Invalid option that should default back to "filename".
1131
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1132
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
1133
    sort($actual);
1134
    $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.');
1135
  }
1136

    
1137
  /**
1138
   * Check that the recurse option decends into subdirectories.
1139
   */
1140
  function testOptionRecurse() {
1141
    $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
1142
    $this->assertTrue(empty($files), "Without recursion couldn't find javascript files.");
1143

    
1144
    $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => TRUE));
1145
    $this->assertEqual(2, count($files), 'With recursion we found the expected javascript files.');
1146
  }
1147

    
1148

    
1149
  /**
1150
   * Check that the min_depth options lets us ignore files in the starting
1151
   * directory.
1152
   */
1153
  function testOptionMinDepth() {
1154
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
1155
    $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.');
1156

    
1157
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
1158
    $this->assertTrue(empty($files), "Minimum-depth of 1 successfully excludes files from current directory.");
1159
  }
1160
}
1161

    
1162
/**
1163
 * Tests the file_scan_directory() function on remote filesystems.
1164
 */
1165
class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
1166
  public static function getInfo() {
1167
    $info = parent::getInfo();
1168
    $info['group'] = 'File API (remote)';
1169
    return $info;
1170
  }
1171

    
1172
  function setUp() {
1173
    parent::setUp('file_test');
1174
    variable_set('file_default_scheme', 'dummy-remote');
1175
  }
1176
}
1177

    
1178
/**
1179
 * Deletion related tests.
1180
 */
1181
class FileUnmanagedDeleteTest extends FileTestCase {
1182
  public static function getInfo() {
1183
    return array(
1184
      'name' => 'Unmanaged file delete',
1185
      'description' => 'Tests the unmanaged file delete function.',
1186
      'group' => 'File API',
1187
    );
1188
  }
1189

    
1190
  /**
1191
   * Delete a normal file.
1192
   */
1193
  function testNormal() {
1194
    // Create a file for testing
1195
    $file = $this->createFile();
1196

    
1197
    // Delete a regular file
1198
    $this->assertTrue(file_unmanaged_delete($file->uri), 'Deleted worked.');
1199
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1200
  }
1201

    
1202
  /**
1203
   * Try deleting a missing file.
1204
   */
1205
  function testMissing() {
1206
    // Try to delete a non-existing file
1207
    $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), 'Returns true when deleting a non-existent file.');
1208
  }
1209

    
1210
  /**
1211
   * Try deleting a directory.
1212
   */
1213
  function testDirectory() {
1214
    // A directory to operate on.
1215
    $directory = $this->createDirectory();
1216

    
1217
    // Try to delete a directory
1218
    $this->assertFalse(file_unmanaged_delete($directory), 'Could not delete the delete directory.');
1219
    $this->assertTrue(file_exists($directory), 'Directory has not been deleted.');
1220
  }
1221
}
1222

    
1223
/**
1224
 * Deletion related tests on remote filesystems.
1225
 */
1226
class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
1227
  public static function getInfo() {
1228
    $info = parent::getInfo();
1229
    $info['group'] = 'File API (remote)';
1230
    return $info;
1231
  }
1232

    
1233
  function setUp() {
1234
    parent::setUp('file_test');
1235
    variable_set('file_default_scheme', 'dummy-remote');
1236
  }
1237
}
1238

    
1239
/**
1240
 * Deletion related tests.
1241
 */
1242
class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
1243
  public static function getInfo() {
1244
    return array(
1245
      'name' => 'Unmanaged recursive file delete',
1246
      'description' => 'Tests the unmanaged file delete recursive function.',
1247
      'group' => 'File API',
1248
    );
1249
  }
1250

    
1251
  /**
1252
   * Delete a normal file.
1253
   */
1254
  function testSingleFile() {
1255
    // Create a file for testing
1256
    $filepath = file_default_scheme() . '://' . $this->randomName();
1257
    file_put_contents($filepath, '');
1258

    
1259
    // Delete the file.
1260
    $this->assertTrue(file_unmanaged_delete_recursive($filepath), 'Function reported success.');
1261
    $this->assertFalse(file_exists($filepath), 'Test file has been deleted.');
1262
  }
1263

    
1264
  /**
1265
   * Try deleting an empty directory.
1266
   */
1267
  function testEmptyDirectory() {
1268
    // A directory to operate on.
1269
    $directory = $this->createDirectory();
1270

    
1271
    // Delete the directory.
1272
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1273
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1274
  }
1275

    
1276
  /**
1277
   * Try deleting a directory with some files.
1278
   */
1279
  function testDirectory() {
1280
    // A directory to operate on.
1281
    $directory = $this->createDirectory();
1282
    $filepathA = $directory . '/A';
1283
    $filepathB = $directory . '/B';
1284
    file_put_contents($filepathA, '');
1285
    file_put_contents($filepathB, '');
1286

    
1287
    // Delete the directory.
1288
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1289
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1290
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1291
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1292
  }
1293

    
1294
  /**
1295
   * Try deleting subdirectories with some files.
1296
   */
1297
  function testSubDirectory() {
1298
    // A directory to operate on.
1299
    $directory = $this->createDirectory();
1300
    $subdirectory = $this->createDirectory($directory . '/sub');
1301
    $filepathA = $directory . '/A';
1302
    $filepathB = $subdirectory . '/B';
1303
    file_put_contents($filepathA, '');
1304
    file_put_contents($filepathB, '');
1305

    
1306
    // Delete the directory.
1307
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1308
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1309
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1310
    $this->assertFalse(file_exists($subdirectory), 'Subdirectory has been deleted.');
1311
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1312
  }
1313
}
1314

    
1315
/**
1316
 * Deletion related tests on remote filesystems.
1317
 */
1318
class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
1319
  public static function getInfo() {
1320
    $info = parent::getInfo();
1321
    $info['group'] = 'File API (remote)';
1322
    return $info;
1323
  }
1324

    
1325
  function setUp() {
1326
    parent::setUp('file_test');
1327
    variable_set('file_default_scheme', 'dummy-remote');
1328
  }
1329
}
1330

    
1331
/**
1332
 * Unmanaged move related tests.
1333
 */
1334
class FileUnmanagedMoveTest extends FileTestCase {
1335
  public static function getInfo() {
1336
    return array(
1337
      'name' => 'Unmanaged file moving',
1338
      'description' => 'Tests the unmanaged file move function.',
1339
      'group' => 'File API',
1340
    );
1341
  }
1342

    
1343
  /**
1344
   * Move a normal file.
1345
   */
1346
  function testNormal() {
1347
    // Create a file for testing
1348
    $file = $this->createFile();
1349

    
1350
    // Moving to a new name.
1351
    $desired_filepath = 'public://' . $this->randomName();
1352
    $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1353
    $this->assertTrue($new_filepath, 'Move was successful.');
1354
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1355
    $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
1356
    $this->assertFalse(file_exists($file->uri), 'No file remains at the old location.');
1357
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1358

    
1359
    // Moving with rename.
1360
    $desired_filepath = 'public://' . $this->randomName();
1361
    $this->assertTrue(file_exists($new_filepath), 'File exists before moving.');
1362
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
1363
    $newer_filepath = file_unmanaged_move($new_filepath, $desired_filepath, FILE_EXISTS_RENAME);
1364
    $this->assertTrue($newer_filepath, 'Move was successful.');
1365
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
1366
    $this->assertTrue(file_exists($newer_filepath), 'File exists at the new location.');
1367
    $this->assertFalse(file_exists($new_filepath), 'No file remains at the old location.');
1368
    $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
1369

    
1370
    // TODO: test moving to a directory (rather than full directory/file path)
1371
    // TODO: test creating and moving normal files (rather than streams)
1372
  }
1373

    
1374
  /**
1375
   * Try to move a missing file.
1376
   */
1377
  function testMissing() {
1378
    // Move non-existent file.
1379
    $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
1380
    $this->assertFalse($new_filepath, 'Moving a missing file fails.');
1381
  }
1382

    
1383
  /**
1384
   * Try to move a file onto itself.
1385
   */
1386
  function testOverwriteSelf() {
1387
    // Create a file for testing.
1388
    $file = $this->createFile();
1389

    
1390
    // Move the file onto itself without renaming shouldn't make changes.
1391
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
1392
    $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
1393
    $this->assertTrue(file_exists($file->uri), 'File exists after moving onto itself.');
1394

    
1395
    // Move the file onto itself with renaming will result in a new filename.
1396
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
1397
    $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
1398
    $this->assertFalse(file_exists($file->uri), 'Original file has been removed.');
1399
    $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
1400
  }
1401
}
1402

    
1403
/**
1404
 * Unmanaged move related tests on remote filesystems.
1405
 */
1406
class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
1407
  public static function getInfo() {
1408
    $info = parent::getInfo();
1409
    $info['group'] = 'File API (remote)';
1410
    return $info;
1411
  }
1412

    
1413
  function setUp() {
1414
    parent::setUp('file_test');
1415
    variable_set('file_default_scheme', 'dummy-remote');
1416
  }
1417
}
1418

    
1419
/**
1420
 * Unmanaged copy related tests.
1421
 */
1422
class FileUnmanagedCopyTest extends FileTestCase {
1423
  public static function getInfo() {
1424
    return array(
1425
      'name' => 'Unmanaged file copying',
1426
      'description' => 'Tests the unmanaged file copy function.',
1427
      'group' => 'File API',
1428
    );
1429
  }
1430

    
1431
  /**
1432
   * Copy a normal file.
1433
   */
1434
  function testNormal() {
1435
    // Create a file for testing
1436
    $file = $this->createFile();
1437

    
1438
    // Copying to a new name.
1439
    $desired_filepath = 'public://' . $this->randomName();
1440
    $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1441
    $this->assertTrue($new_filepath, 'Copy was successful.');
1442
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1443
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1444
    $this->assertTrue(file_exists($new_filepath), 'New file exists.');
1445
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1446

    
1447
    // Copying with rename.
1448
    $desired_filepath = 'public://' . $this->randomName();
1449
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
1450
    $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
1451
    $this->assertTrue($newer_filepath, 'Copy was successful.');
1452
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
1453
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1454
    $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
1455
    $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
1456

    
1457
    // TODO: test copying to a directory (rather than full directory/file path)
1458
    // TODO: test copying normal files using normal paths (rather than only streams)
1459
  }
1460

    
1461
  /**
1462
   * Copy a non-existent file.
1463
   */
1464
  function testNonExistent() {
1465
    // Copy non-existent file
1466
    $desired_filepath = $this->randomName();
1467
    $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
1468
    $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
1469
    $this->assertFalse($new_filepath, 'Copying a missing file fails.');
1470
  }
1471

    
1472
  /**
1473
   * Copy a file onto itself.
1474
   */
1475
  function testOverwriteSelf() {
1476
    // Create a file for testing
1477
    $file = $this->createFile();
1478

    
1479
    // Copy the file onto itself with renaming works.
1480
    $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
1481
    $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
1482
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1483
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1484
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1485
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1486

    
1487
    // Copy the file onto itself without renaming fails.
1488
    $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_ERROR);
1489
    $this->assertFalse($new_filepath, 'Copying onto itself without renaming fails.');
1490
    $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
1491

    
1492
    // Copy the file into same directory without renaming fails.
1493
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
1494
    $this->assertFalse($new_filepath, 'Copying onto itself fails.');
1495
    $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
1496

    
1497
    // Copy the file into same directory with renaming works.
1498
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
1499
    $this->assertTrue($new_filepath, 'Copying into same directory works.');
1500
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1501
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1502
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1503
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1504
  }
1505
}
1506

    
1507
/**
1508
 * Unmanaged copy related tests on remote filesystems.
1509
 */
1510
class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
1511
  public static function getInfo() {
1512
    $info = parent::getInfo();
1513
    $info['group'] = 'File API (remote)';
1514
    return $info;
1515
  }
1516

    
1517
  function setUp() {
1518
    parent::setUp('file_test');
1519
    variable_set('file_default_scheme', 'dummy-remote');
1520
  }
1521
}
1522

    
1523
/**
1524
 * Deletion related tests.
1525
 */
1526
class FileDeleteTest extends FileHookTestCase {
1527
  public static function getInfo() {
1528
    return array(
1529
      'name' => 'File delete',
1530
      'description' => 'Tests the file delete function.',
1531
      'group' => 'File API',
1532
    );
1533
  }
1534

    
1535
  /**
1536
   * Tries deleting a normal file (as opposed to a directory, symlink, etc).
1537
   */
1538
  function testUnused() {
1539
    $file = $this->createFile();
1540

    
1541
    // Check that deletion removes the file and database record.
1542
    $this->assertTrue(is_file($file->uri), 'File exists.');
1543
    $this->assertIdentical(file_delete($file), TRUE, 'Delete worked.');
1544
    $this->assertFileHooksCalled(array('delete'));
1545
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1546
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1547
  }
1548

    
1549
  /**
1550
   * Tries deleting a file that is in use.
1551
   */
1552
  function testInUse() {
1553
    $file = $this->createFile();
1554
    file_usage_add($file, 'testing', 'test', 1);
1555
    file_usage_add($file, 'testing', 'test', 1);
1556

    
1557
    file_usage_delete($file, 'testing', 'test', 1);
1558
    file_delete($file);
1559
    $usage = file_usage_list($file);
1560
    $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
1561
    $this->assertTrue(file_exists($file->uri), 'File still exists on the disk.');
1562
    $this->assertTrue(file_load($file->fid), 'File still exists in the database.');
1563

    
1564
    // Clear out the call to hook_file_load().
1565
    file_test_reset();
1566

    
1567
    file_usage_delete($file, 'testing', 'test', 1);
1568
    file_delete($file);
1569
    $usage = file_usage_list($file);
1570
    $this->assertFileHooksCalled(array('delete'));
1571
    $this->assertTrue(empty($usage), 'File usage data was removed.');
1572
    $this->assertFalse(file_exists($file->uri), 'File has been deleted after its last usage was removed.');
1573
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1574
  }
1575
}
1576

    
1577

    
1578
/**
1579
 * Move related tests
1580
 */
1581
class FileMoveTest extends FileHookTestCase {
1582
  public static function getInfo() {
1583
    return array(
1584
      'name' => 'File moving',
1585
      'description' => 'Tests the file move function.',
1586
      'group' => 'File API',
1587
    );
1588
  }
1589

    
1590
  /**
1591
   * Move a normal file.
1592
   */
1593
  function testNormal() {
1594
    $contents = $this->randomName(10);
1595
    $source = $this->createFile(NULL, $contents);
1596
    $desired_filepath = 'public://' . $this->randomName();
1597

    
1598
    // Clone the object so we don't have to worry about the function changing
1599
    // our reference copy.
1600
    $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
1601

    
1602
    // Check the return status and that the contents changed.
1603
    $this->assertTrue($result, 'File moved successfully.');
1604
    $this->assertFalse(file_exists($source->uri));
1605
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1606

    
1607
    // Check that the correct hooks were called.
1608
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1609

    
1610
    // Make sure we got the same file back.
1611
    $this->assertEqual($source->fid, $result->fid, format_string("Source file id's' %fid is unchanged after move.", array('%fid' => $source->fid)));
1612

    
1613
    // Reload the file from the database and check that the changes were
1614
    // actually saved.
1615
    $loaded_file = file_load($result->fid, TRUE);
1616
    $this->assertTrue($loaded_file, 'File can be loaded from the database.');
1617
    $this->assertFileUnchanged($result, $loaded_file);
1618
  }
1619

    
1620
  /**
1621
   * Test renaming when moving onto a file that already exists.
1622
   */
1623
  function testExistingRename() {
1624
    // Setup a file to overwrite.
1625
    $contents = $this->randomName(10);
1626
    $source = $this->createFile(NULL, $contents);
1627
    $target = $this->createFile();
1628
    $this->assertDifferentFile($source, $target);
1629

    
1630
    // Clone the object so we don't have to worry about the function changing
1631
    // our reference copy.
1632
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_RENAME);
1633

    
1634
    // Check the return status and that the contents changed.
1635
    $this->assertTrue($result, 'File moved successfully.');
1636
    $this->assertFalse(file_exists($source->uri));
1637
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1638

    
1639
    // Check that the correct hooks were called.
1640
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1641

    
1642
    // Compare the returned value to what made it into the database.
1643
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1644
    // The target file should not have been altered.
1645
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1646
    // Make sure we end up with two distinct files afterwards.
1647
    $this->assertDifferentFile($target, $result);
1648

    
1649
    // Compare the source and results.
1650
    $loaded_source = file_load($source->fid, TRUE);
1651
    $this->assertEqual($loaded_source->fid, $result->fid, "Returned file's id matches the source.");
1652
    $this->assertNotEqual($loaded_source->uri, $source->uri, 'Returned file path has changed from the original.');
1653
  }
1654

    
1655
  /**
1656
   * Test replacement when moving onto a file that already exists.
1657
   */
1658
  function testExistingReplace() {
1659
    // Setup a file to overwrite.
1660
    $contents = $this->randomName(10);
1661
    $source = $this->createFile(NULL, $contents);
1662
    $target = $this->createFile();
1663
    $this->assertDifferentFile($source, $target);
1664

    
1665
    // Clone the object so we don't have to worry about the function changing
1666
    // our reference copy.
1667
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_REPLACE);
1668

    
1669
    // Look at the results.
1670
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
1671
    $this->assertFalse(file_exists($source->uri));
1672
    $this->assertTrue($result, 'File moved successfully.');
1673

    
1674
    // Check that the correct hooks were called.
1675
    $this->assertFileHooksCalled(array('move', 'update', 'delete', 'load'));
1676

    
1677
    // Reload the file from the database and check that the changes were
1678
    // actually saved.
1679
    $loaded_result = file_load($result->fid, TRUE);
1680
    $this->assertFileUnchanged($result, $loaded_result);
1681
    // Check that target was re-used.
1682
    $this->assertSameFile($target, $loaded_result);
1683
    // Source and result should be totally different.
1684
    $this->assertDifferentFile($source, $loaded_result);
1685
  }
1686

    
1687
  /**
1688
   * Test replacement when moving onto itself.
1689
   */
1690
  function testExistingReplaceSelf() {
1691
    // Setup a file to overwrite.
1692
    $contents = $this->randomName(10);
1693
    $source = $this->createFile(NULL, $contents);
1694

    
1695
    // Copy the file over itself. Clone the object so we don't have to worry
1696
    // about the function changing our reference copy.
1697
    $result = file_move(clone $source, $source->uri, FILE_EXISTS_REPLACE);
1698
    $this->assertFalse($result, 'File move failed.');
1699
    $this->assertEqual($contents, file_get_contents($source->uri), 'Contents of file were not altered.');
1700

    
1701
    // Check that no hooks were called while failing.
1702
    $this->assertFileHooksCalled(array());
1703

    
1704
    // Load the file from the database and make sure it is identical to what
1705
    // was returned.
1706
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1707
  }
1708

    
1709
  /**
1710
   * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
1711
   * specified.
1712
   */
1713
  function testExistingError() {
1714
    $contents = $this->randomName(10);
1715
    $source = $this->createFile();
1716
    $target = $this->createFile(NULL, $contents);
1717
    $this->assertDifferentFile($source, $target);
1718

    
1719
    // Clone the object so we don't have to worry about the function changing
1720
    // our reference copy.
1721
    $result = file_move(clone $source, $target->uri, FILE_EXISTS_ERROR);
1722

    
1723
    // Check the return status and that the contents did not change.
1724
    $this->assertFalse($result, 'File move failed.');
1725
    $this->assertTrue(file_exists($source->uri));
1726
    $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
1727

    
1728
    // Check that no hooks were called while failing.
1729
    $this->assertFileHooksCalled(array());
1730

    
1731
    // Load the file from the database and make sure it is identical to what
1732
    // was returned.
1733
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1734
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1735
  }
1736
}
1737

    
1738

    
1739
/**
1740
 * Copy related tests.
1741
 */
1742
class FileCopyTest extends FileHookTestCase {
1743
  public static function getInfo() {
1744
    return array(
1745
      'name' => 'File copying',
1746
      'description' => 'Tests the file copy function.',
1747
      'group' => 'File API',
1748
    );
1749
  }
1750

    
1751
  /**
1752
   * Test file copying in the normal, base case.
1753
   */
1754
  function testNormal() {
1755
    $contents = $this->randomName(10);
1756
    $source = $this->createFile(NULL, $contents);
1757
    $desired_uri = 'public://' . $this->randomName();
1758

    
1759
    // Clone the object so we don't have to worry about the function changing
1760
    // our reference copy.
1761
    $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
1762

    
1763
    // Check the return status and that the contents changed.
1764
    $this->assertTrue($result, 'File copied successfully.');
1765
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
1766

    
1767
    // Check that the correct hooks were called.
1768
    $this->assertFileHooksCalled(array('copy', 'insert'));
1769

    
1770
    $this->assertDifferentFile($source, $result);
1771
    $this->assertEqual($result->uri, $desired_uri, 'The copied file object has the desired filepath.');
1772
    $this->assertTrue(file_exists($source->uri), 'The original file still exists.');
1773
    $this->assertTrue(file_exists($result->uri), 'The copied file exists.');
1774

    
1775
    // Reload the file from the database and check that the changes were
1776
    // actually saved.
1777
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1778
  }
1779

    
1780
  /**
1781
   * Test renaming when copying over a file that already exists.
1782
   */
1783
  function testExistingRename() {
1784
    // Setup a file to overwrite.
1785
    $contents = $this->randomName(10);
1786
    $source = $this->createFile(NULL, $contents);
1787
    $target = $this->createFile();
1788
    $this->assertDifferentFile($source, $target);
1789

    
1790
    // Clone the object so we don't have to worry about the function changing
1791
    // our reference copy.
1792
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_RENAME);
1793

    
1794
    // Check the return status and that the contents changed.
1795
    $this->assertTrue($result, 'File copied successfully.');
1796
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
1797
    $this->assertNotEqual($result->uri, $source->uri, 'Returned file path has changed from the original.');
1798

    
1799
    // Check that the correct hooks were called.
1800
    $this->assertFileHooksCalled(array('copy', 'insert'));
1801

    
1802
    // Load all the affected files to check the changes that actually made it
1803
    // to the database.
1804
    $loaded_source = file_load($source->fid, TRUE);
1805
    $loaded_target = file_load($target->fid, TRUE);
1806
    $loaded_result = file_load($result->fid, TRUE);
1807

    
1808
    // Verify that the source file wasn't changed.
1809
    $this->assertFileUnchanged($source, $loaded_source);
1810

    
1811
    // Verify that what was returned is what's in the database.
1812
    $this->assertFileUnchanged($result, $loaded_result);
1813

    
1814
    // Make sure we end up with three distinct files afterwards.
1815
    $this->assertDifferentFile($loaded_source, $loaded_target);
1816
    $this->assertDifferentFile($loaded_target, $loaded_result);
1817
    $this->assertDifferentFile($loaded_source, $loaded_result);
1818
  }
1819

    
1820
  /**
1821
   * Test replacement when copying over a file that already exists.
1822
   */
1823
  function testExistingReplace() {
1824
    // Setup a file to overwrite.
1825
    $contents = $this->randomName(10);
1826
    $source = $this->createFile(NULL, $contents);
1827
    $target = $this->createFile();
1828
    $this->assertDifferentFile($source, $target);
1829

    
1830
    // Clone the object so we don't have to worry about the function changing
1831
    // our reference copy.
1832
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_REPLACE);
1833

    
1834
    // Check the return status and that the contents changed.
1835
    $this->assertTrue($result, 'File copied successfully.');
1836
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
1837
    $this->assertDifferentFile($source, $result);
1838

    
1839
    // Check that the correct hooks were called.
1840
    $this->assertFileHooksCalled(array('load', 'copy', 'update'));
1841

    
1842
    // Load all the affected files to check the changes that actually made it
1843
    // to the database.
1844
    $loaded_source = file_load($source->fid, TRUE);
1845
    $loaded_target = file_load($target->fid, TRUE);
1846
    $loaded_result = file_load($result->fid, TRUE);
1847

    
1848
    // Verify that the source file wasn't changed.
1849
    $this->assertFileUnchanged($source, $loaded_source);
1850

    
1851
    // Verify that what was returned is what's in the database.
1852
    $this->assertFileUnchanged($result, $loaded_result);
1853

    
1854
    // Target file was reused for the result.
1855
    $this->assertFileUnchanged($loaded_target, $loaded_result);
1856
  }
1857

    
1858
  /**
1859
   * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
1860
   * specified.
1861
   */
1862
  function testExistingError() {
1863
    $contents = $this->randomName(10);
1864
    $source = $this->createFile();
1865
    $target = $this->createFile(NULL, $contents);
1866
    $this->assertDifferentFile($source, $target);
1867

    
1868
    // Clone the object so we don't have to worry about the function changing
1869
    // our reference copy.
1870
    $result = file_copy(clone $source, $target->uri, FILE_EXISTS_ERROR);
1871

    
1872
    // Check the return status and that the contents were not changed.
1873
    $this->assertFalse($result, 'File copy failed.');
1874
    $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
1875

    
1876
    // Check that the correct hooks were called.
1877
    $this->assertFileHooksCalled(array());
1878

    
1879
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1880
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1881
  }
1882
}
1883

    
1884

    
1885
/**
1886
 * Tests the file_load() function.
1887
 */
1888
class FileLoadTest extends FileHookTestCase {
1889
  public static function getInfo() {
1890
    return array(
1891
      'name' => 'File loading',
1892
      'description' => 'Tests the file_load() function.',
1893
      'group' => 'File API',
1894
    );
1895
  }
1896

    
1897
  /**
1898
   * Try to load a non-existent file by fid.
1899
   */
1900
  function testLoadMissingFid() {
1901
    $this->assertFalse(file_load(-1), "Try to load an invalid fid fails.");
1902
    $this->assertFileHooksCalled(array());
1903
  }
1904

    
1905
  /**
1906
   * Try to load a non-existent file by URI.
1907
   */
1908
  function testLoadMissingFilepath() {
1909
    $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
1910
    $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
1911
    $this->assertFileHooksCalled(array());
1912
  }
1913

    
1914
  /**
1915
   * Try to load a non-existent file by status.
1916
   */
1917
  function testLoadInvalidStatus() {
1918
    $files = file_load_multiple(array(), array('status' => -99));
1919
    $this->assertFalse(reset($files), "Trying to load a file with an invalid status fails.");
1920
    $this->assertFileHooksCalled(array());
1921
  }
1922

    
1923
  /**
1924
   * Load a single file and ensure that the correct values are returned.
1925
   */
1926
  function testSingleValues() {
1927
    // Create a new file object from scratch so we know the values.
1928
    $file = $this->createFile('druplicon.txt', NULL, 'public');
1929

    
1930
    $by_fid_file = file_load($file->fid);
1931
    $this->assertFileHookCalled('load');
1932
    $this->assertTrue(is_object($by_fid_file), 'file_load() returned an object.');
1933
    $this->assertEqual($by_fid_file->fid, $file->fid, 'Loading by fid got the same fid.', 'File');
1934
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
1935
    $this->assertEqual($by_fid_file->filename, $file->filename, 'Loading by fid got the correct filename.', 'File');
1936
    $this->assertEqual($by_fid_file->filemime, $file->filemime, 'Loading by fid got the correct MIME type.', 'File');
1937
    $this->assertEqual($by_fid_file->status, $file->status, 'Loading by fid got the correct status.', 'File');
1938
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
1939
  }
1940

    
1941
  /**
1942
   * This will test loading file data from the database.
1943
   */
1944
  function testMultiple() {
1945
    // Create a new file object.
1946
    $file = $this->createFile('druplicon.txt', NULL, 'public');
1947

    
1948
    // Load by path.
1949
    file_test_reset();
1950
    $by_path_files = file_load_multiple(array(), array('uri' => $file->uri));
1951
    $this->assertFileHookCalled('load');
1952
    $this->assertEqual(1, count($by_path_files), 'file_load_multiple() returned an array of the correct size.');
1953
    $by_path_file = reset($by_path_files);
1954
    $this->assertTrue($by_path_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
1955
    $this->assertEqual($by_path_file->fid, $file->fid, 'Loading by filepath got the correct fid.', 'File');
1956

    
1957
    // Load by fid.
1958
    file_test_reset();
1959
    $by_fid_files = file_load_multiple(array($file->fid), array());
1960
    $this->assertFileHookCalled('load');
1961
    $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
1962
    $by_fid_file = reset($by_fid_files);
1963
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
1964
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
1965
  }
1966
}
1967

    
1968
/**
1969
 * Tests the file_save() function.
1970
 */
1971
class FileSaveTest extends FileHookTestCase {
1972
  public static function getInfo() {
1973
    return array(
1974
      'name' => 'File saving',
1975
      'description' => 'Tests the file_save() function.',
1976
      'group' => 'File API',
1977
    );
1978
  }
1979

    
1980
  function testFileSave() {
1981
    // Create a new file object.
1982
    $file = array(
1983
      'uid' => 1,
1984
      'filename' => 'druplicon.txt',
1985
      'uri' => 'public://druplicon.txt',
1986
      'filemime' => 'text/plain',
1987
      'timestamp' => 1,
1988
      'status' => FILE_STATUS_PERMANENT,
1989
    );
1990
    $file = (object) $file;
1991
    file_put_contents($file->uri, 'hello world');
1992

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

    
1996
    // Check that the correct hooks were called.
1997
    $this->assertFileHooksCalled(array('insert'));
1998

    
1999
    $this->assertNotNull($saved_file, 'Saving the file should give us back a file object.', 'File');
2000
    $this->assertTrue($saved_file->fid > 0, 'A new file ID is set when saving a new file to the database.', 'File');
2001
    $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
2002
    $this->assertNotNull($loaded_file, 'Record exists in the database.');
2003
    $this->assertEqual($loaded_file->status, $file->status, 'Status was saved correctly.');
2004
    $this->assertEqual($saved_file->filesize, filesize($file->uri), 'File size was set correctly.', 'File');
2005
    $this->assertTrue($saved_file->timestamp > 1, 'File size was set correctly.', 'File');
2006

    
2007

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

    
2013
    // Check that the correct hooks were called.
2014
    $this->assertFileHooksCalled(array('load', 'update'));
2015

    
2016
    $this->assertEqual($resaved_file->fid, $saved_file->fid, 'The file ID of an existing file is not changed when updating the database.', 'File');
2017
    $this->assertTrue($resaved_file->timestamp >= $saved_file->timestamp, "Timestamp didn't go backwards.", 'File');
2018
    $loaded_file = db_query('SELECT * FROM {file_managed} f WHERE f.fid = :fid', array(':fid' => $saved_file->fid))->fetch(PDO::FETCH_OBJ);
2019
    $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
2020
    $this->assertEqual($loaded_file->status, $saved_file->status, 'Status was saved correctly.');
2021

    
2022
    // Try to insert a second file with the same name apart from case insensitivity
2023
    // to ensure the 'uri' index allows for filenames with different cases.
2024
    $file = (object) array(
2025
      'uid' => 1,
2026
      'filename' => 'DRUPLICON.txt',
2027
      'uri' => 'public://DRUPLICON.txt',
2028
      'filemime' => 'text/plain',
2029
      'timestamp' => 1,
2030
      'status' => FILE_STATUS_PERMANENT,
2031
    );
2032
    file_put_contents($file->uri, 'hello world');
2033
    file_save($file);
2034
  }
2035
}
2036

    
2037
/**
2038
 * Tests file usage functions.
2039
 */
2040
class FileUsageTest extends FileTestCase {
2041
  public static function getInfo() {
2042
    return array(
2043
      'name' => 'File usage',
2044
      'description' => 'Tests the file usage functions.',
2045
      'group' => 'File',
2046
    );
2047
  }
2048

    
2049
  /**
2050
   * Tests file_usage_list().
2051
   */
2052
  function testGetUsage() {
2053
    $file = $this->createFile();
2054
    db_insert('file_usage')
2055
      ->fields(array(
2056
        'fid' => $file->fid,
2057
        'module' => 'testing',
2058
        'type' => 'foo',
2059
        'id' => 1,
2060
        'count' => 1
2061
      ))
2062
      ->execute();
2063
    db_insert('file_usage')
2064
      ->fields(array(
2065
        'fid' => $file->fid,
2066
        'module' => 'testing',
2067
        'type' => 'bar',
2068
        'id' => 2,
2069
        'count' => 2
2070
      ))
2071
      ->execute();
2072

    
2073
    $usage = file_usage_list($file);
2074

    
2075
    $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
2076
    $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
2077
    $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
2078
    $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
2079
    $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
2080
  }
2081

    
2082
  /**
2083
   * Tests file_usage_add().
2084
   */
2085
  function testAddUsage() {
2086
    $file = $this->createFile();
2087
    file_usage_add($file, 'testing', 'foo', 1);
2088
    // Add the file twice to ensure that the count is incremented rather than
2089
    // creating additional records.
2090
    file_usage_add($file, 'testing', 'bar', 2);
2091
    file_usage_add($file, 'testing', 'bar', 2);
2092

    
2093
    $usage = db_select('file_usage', 'f')
2094
      ->fields('f')
2095
      ->condition('f.fid', $file->fid)
2096
      ->execute()
2097
      ->fetchAllAssoc('id');
2098
    $this->assertEqual(count($usage), 2, 'Created two records');
2099
    $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
2100
    $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
2101
    $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
2102
    $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
2103
    $this->assertEqual($usage[1]->count, 1, 'Correct count');
2104
    $this->assertEqual($usage[2]->count, 2, 'Correct count');
2105
  }
2106

    
2107
  /**
2108
   * Tests file_usage_delete().
2109
   */
2110
  function testRemoveUsage() {
2111
    $file = $this->createFile();
2112
    db_insert('file_usage')
2113
      ->fields(array(
2114
        'fid' => $file->fid,
2115
        'module' => 'testing',
2116
        'type' => 'bar',
2117
        'id' => 2,
2118
        'count' => 3,
2119
      ))
2120
      ->execute();
2121

    
2122
    // Normal decrement.
2123
    file_usage_delete($file, 'testing', 'bar', 2);
2124
    $count = db_select('file_usage', 'f')
2125
      ->fields('f', array('count'))
2126
      ->condition('f.fid', $file->fid)
2127
      ->execute()
2128
      ->fetchField();
2129
    $this->assertEqual(2, $count, 'The count was decremented correctly.');
2130

    
2131
    // Multiple decrement and removal.
2132
    file_usage_delete($file, 'testing', 'bar', 2, 2);
2133
    $count = db_select('file_usage', 'f')
2134
      ->fields('f', array('count'))
2135
      ->condition('f.fid', $file->fid)
2136
      ->execute()
2137
      ->fetchField();
2138
    $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
2139

    
2140
    // Non-existent decrement.
2141
    file_usage_delete($file, 'testing', 'bar', 2);
2142
    $count = db_select('file_usage', 'f')
2143
      ->fields('f', array('count'))
2144
      ->condition('f.fid', $file->fid)
2145
      ->execute()
2146
      ->fetchField();
2147
    $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
2148
  }
2149
}
2150

    
2151
/**
2152
 * Tests the file_validate() function..
2153
 */
2154
class FileValidateTest extends FileHookTestCase {
2155
  public static function getInfo() {
2156
    return array(
2157
      'name' => 'File validate',
2158
      'description' => 'Tests the file_validate() function.',
2159
      'group' => 'File API',
2160
    );
2161
  }
2162

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

    
2169
    // Empty validators.
2170
    $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
2171
    $this->assertFileHooksCalled(array('validate'));
2172

    
2173
    // Use the file_test.module's test validator to ensure that passing tests
2174
    // return correctly.
2175
    file_test_reset();
2176
    file_test_set_return('validate', array());
2177
    $passing = array('file_test_validator' => array(array()));
2178
    $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
2179
    $this->assertFileHooksCalled(array('validate'));
2180

    
2181
    // Now test for failures in validators passed in and by hook_validate.
2182
    file_test_reset();
2183
    file_test_set_return('validate', array('Epic fail'));
2184
    $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
2185
    $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
2186
    $this->assertFileHooksCalled(array('validate'));
2187
  }
2188
}
2189

    
2190
/**
2191
 *  Tests the file_save_data() function.
2192
 */
2193
class FileSaveDataTest extends FileHookTestCase {
2194
  public static function getInfo() {
2195
    return array(
2196
      'name' => 'File save data',
2197
      'description' => 'Tests the file save data function.',
2198
      'group' => 'File API',
2199
    );
2200
  }
2201

    
2202
  /**
2203
   * Test the file_save_data() function when no filename is provided.
2204
   */
2205
  function testWithoutFilename() {
2206
    $contents = $this->randomName(8);
2207

    
2208
    $result = file_save_data($contents);
2209
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2210

    
2211
    $this->assertEqual(file_default_scheme(), file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2212
    $this->assertEqual($result->filename, drupal_basename($result->uri), "Filename was set to the file's basename.");
2213
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2214
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2215
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2216

    
2217
    // Check that the correct hooks were called.
2218
    $this->assertFileHooksCalled(array('insert'));
2219

    
2220
    // Verify that what was returned is what's in the database.
2221
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2222
  }
2223

    
2224
  /**
2225
   * Test the file_save_data() function when a filename is provided.
2226
   */
2227
  function testWithFilename() {
2228
    $contents = $this->randomName(8);
2229

    
2230
    // Using filename with non-latin characters.
2231
    $filename = 'Текстовый файл.txt';
2232

    
2233
    $result = file_save_data($contents, 'public://' . $filename);
2234
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2235

    
2236
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2237
    $this->assertEqual($filename, drupal_basename($result->uri), 'File was named correctly.');
2238
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2239
    $this->assertEqual($result->filemime, 'text/plain', 'A MIME type was set.');
2240
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2241

    
2242
    // Check that the correct hooks were called.
2243
    $this->assertFileHooksCalled(array('insert'));
2244

    
2245
    // Verify that what was returned is what's in the database.
2246
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2247
  }
2248

    
2249
  /**
2250
   * Test file_save_data() when renaming around an existing file.
2251
   */
2252
  function testExistingRename() {
2253
    // Setup a file to overwrite.
2254
    $existing = $this->createFile();
2255
    $contents = $this->randomName(8);
2256

    
2257
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
2258
    $this->assertTrue($result, 'File saved successfully.');
2259

    
2260
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2261
    $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the source, rather than that of the renamed file.');
2262
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2263
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2264
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2265

    
2266
    // Check that the correct hooks were called.
2267
    $this->assertFileHooksCalled(array('insert'));
2268

    
2269
    // Ensure that the existing file wasn't overwritten.
2270
    $this->assertDifferentFile($existing, $result);
2271
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2272

    
2273
    // Verify that was returned is what's in the database.
2274
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2275
  }
2276

    
2277
  /**
2278
   * Test file_save_data() when replacing an existing file.
2279
   */
2280
  function testExistingReplace() {
2281
    // Setup a file to overwrite.
2282
    $existing = $this->createFile();
2283
    $contents = $this->randomName(8);
2284

    
2285
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
2286
    $this->assertTrue($result, 'File saved successfully.');
2287

    
2288
    $this->assertEqual('public', file_uri_scheme($result->uri), "File was placed in Drupal's files directory.");
2289
    $this->assertEqual($result->filename, $existing->filename, 'Filename was set to the basename of the existing file, rather than preserving the original name.');
2290
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of the file are correct.');
2291
    $this->assertEqual($result->filemime, 'application/octet-stream', 'A MIME type was set.');
2292
    $this->assertEqual($result->status, FILE_STATUS_PERMANENT, "The file's status was set to permanent.");
2293

    
2294
    // Check that the correct hooks were called.
2295
    $this->assertFileHooksCalled(array('load', 'update'));
2296

    
2297
    // Verify that the existing file was re-used.
2298
    $this->assertSameFile($existing, $result);
2299

    
2300
    // Verify that what was returned is what's in the database.
2301
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2302
  }
2303

    
2304
  /**
2305
   * Test that file_save_data() fails overwriting an existing file.
2306
   */
2307
  function testExistingError() {
2308
    $contents = $this->randomName(8);
2309
    $existing = $this->createFile(NULL, $contents);
2310

    
2311
    // Check the overwrite error.
2312
    $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
2313
    $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
2314
    $this->assertEqual($contents, file_get_contents($existing->uri), 'Contents of existing file were unchanged.');
2315

    
2316
    // Check that no hooks were called while failing.
2317
    $this->assertFileHooksCalled(array());
2318

    
2319
    // Ensure that the existing file wasn't overwritten.
2320
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2321
  }
2322
}
2323

    
2324
/**
2325
 * Tests for download/file transfer functions.
2326
 */
2327
class FileDownloadTest extends FileTestCase {
2328
  public static function getInfo() {
2329
    return array(
2330
      'name' => 'File download',
2331
      'description' => 'Tests for file download/transfer functions.',
2332
      'group' => 'File API',
2333
    );
2334
  }
2335

    
2336
  function setUp() {
2337
    parent::setUp('file_test');
2338
    // Clear out any hook calls.
2339
    file_test_reset();
2340
  }
2341

    
2342
  /**
2343
   * Test the public file transfer system.
2344
   */
2345
  function testPublicFileTransfer() {
2346
    // Test generating an URL to a created file.
2347
    $file = $this->createFile();
2348
    $url = file_create_url($file->uri);
2349
    // URLs can't contain characters outside the ASCII set so $filename has to be
2350
    // encoded.
2351
    $filename = $GLOBALS['base_url'] . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . rawurlencode($file->filename);
2352
    $this->assertEqual($filename, $url, 'Correctly generated a URL for a created file.');
2353
    $this->drupalHead($url);
2354
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the created file.');
2355

    
2356
    // Test generating an URL to a shipped file (i.e. a file that is part of
2357
    // Drupal core, a module or a theme, for example a JavaScript file).
2358
    $filepath = 'misc/jquery.js';
2359
    $url = file_create_url($filepath);
2360
    $this->assertEqual($GLOBALS['base_url'] . '/' . $filepath, $url, 'Correctly generated a URL for a shipped file.');
2361
    $this->drupalHead($url);
2362
    $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
2363
  }
2364

    
2365
  /**
2366
   * Test the private file transfer system.
2367
   */
2368
  function testPrivateFileTransfer() {
2369
    // Set file downloads to private so handler functions get called.
2370

    
2371
    // Create a file.
2372
    $contents = $this->randomName(8);
2373
    $file = $this->createFile(NULL, $contents, 'private');
2374
    $url  = file_create_url($file->uri);
2375

    
2376
    // Set file_test access header to allow the download.
2377
    file_test_set_return('download', array('x-foo' => 'Bar'));
2378
    $this->drupalGet($url);
2379
    $headers = $this->drupalGetHeaders();
2380
    $this->assertEqual($headers['x-foo'], 'Bar', 'Found header set by file_test module on private download.');
2381
    $this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
2382

    
2383
    // Test that the file transferred correctly.
2384
    $this->assertEqual($contents, $this->content, 'Contents of the file are correct.');
2385

    
2386
    // Deny access to all downloads via a -1 header.
2387
    file_test_set_return('download', -1);
2388
    $this->drupalHead($url);
2389
    $this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
2390

    
2391
    // Try non-existent file.
2392
    $url = file_create_url('private://' . $this->randomName());
2393
    $this->drupalHead($url);
2394
    $this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
2395
  }
2396

    
2397
  /**
2398
   * Test file_create_url().
2399
   */
2400
  function testFileCreateUrl() {
2401
    global $base_url;
2402

    
2403
    // Tilde (~) is excluded from this test because it is encoded by
2404
    // rawurlencode() in PHP 5.2 but not in PHP 5.3, as per RFC 3986.
2405
    // @see http://www.php.net/manual/en/function.rawurlencode.php#86506
2406
    $basename = " -._!$'\"()*@[]?&+%#,;=:\n\x00" . // "Special" ASCII characters.
2407
      "%23%25%26%2B%2F%3F" . // Characters that look like a percent-escaped string.
2408
      "éøïвβ中國書۞"; // Characters from various non-ASCII alphabets.
2409
    $basename_encoded = '%20-._%21%24%27%22%28%29%2A%40%5B%5D%3F%26%2B%25%23%2C%3B%3D%3A__' .
2410
      '%2523%2525%2526%252B%252F%253F' .
2411
      '%C3%A9%C3%B8%C3%AF%D0%B2%CE%B2%E4%B8%AD%E5%9C%8B%E6%9B%B8%DB%9E';
2412

    
2413
    $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
2414
    $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
2415
    $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
2416
  }
2417

    
2418
  /**
2419
   * Download a file from the URL generated by file_create_url().
2420
   *
2421
   * Create a file with the specified scheme, directory and filename; check that
2422
   * the URL generated by file_create_url() for the specified file equals the
2423
   * specified URL; fetch the URL and then compare the contents to the file.
2424
   *
2425
   * @param $scheme
2426
   *   A scheme, e.g. "public"
2427
   * @param $directory
2428
   *   A directory, possibly ""
2429
   * @param $filename
2430
   *   A filename
2431
   * @param $expected_url
2432
   *   The expected URL
2433
   * @param $clean_url
2434
   *   The value of the clean_url setting
2435
   */
2436
  private function checkUrl($scheme, $directory, $filename, $expected_url, $clean_url = '1') {
2437
    variable_set('clean_url', $clean_url);
2438

    
2439
    // Convert $filename to a valid filename, i.e. strip characters not
2440
    // supported by the filesystem, and create the file in the specified
2441
    // directory.
2442
    $filepath = file_create_filename($filename, $directory);
2443
    $directory_uri = $scheme . '://' . dirname($filepath);
2444
    file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
2445
    $file = $this->createFile($filepath, NULL, $scheme);
2446

    
2447
    $url = file_create_url($file->uri);
2448
    $this->assertEqual($url, $expected_url, 'Generated URL matches expected URL.');
2449

    
2450
    if ($scheme == 'private') {
2451
      // Tell the implementation of hook_file_download() in file_test.module
2452
      // that this file may be downloaded.
2453
      file_test_set_return('download', array('x-foo' => 'Bar'));
2454
    }
2455

    
2456
    $this->drupalGet($url);
2457
    if ($this->assertResponse(200) == 'pass') {
2458
      $this->assertRaw(file_get_contents($file->uri), 'Contents of the file are correct.');
2459
    }
2460

    
2461
    file_delete($file);
2462
  }
2463
}
2464

    
2465
/**
2466
 * Tests for file URL rewriting.
2467
 */
2468
class FileURLRewritingTest extends FileTestCase {
2469
  public static function getInfo() {
2470
    return array(
2471
      'name' => 'File URL rewriting',
2472
      'description' => 'Tests for file URL rewriting.',
2473
      'group' => 'File',
2474
    );
2475
  }
2476

    
2477
  function setUp() {
2478
    parent::setUp('file_test');
2479
  }
2480

    
2481
  /**
2482
   * Test the generating of rewritten shipped file URLs.
2483
   */
2484
  function testShippedFileURL()  {
2485
    // Test generating an URL to a shipped file (i.e. a file that is part of
2486
    // Drupal core, a module or a theme, for example a JavaScript file).
2487

    
2488
    // Test alteration of file URLs to use a CDN.
2489
    variable_set('file_test_hook_file_url_alter', 'cdn');
2490
    $filepath = 'misc/jquery.js';
2491
    $url = file_create_url($filepath);
2492
    $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2493
    $filepath = 'misc/favicon.ico';
2494
    $url = file_create_url($filepath);
2495
    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2496

    
2497
    // Test alteration of file URLs to use root-relative URLs.
2498
    variable_set('file_test_hook_file_url_alter', 'root-relative');
2499
    $filepath = 'misc/jquery.js';
2500
    $url = file_create_url($filepath);
2501
    $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
2502
    $filepath = 'misc/favicon.ico';
2503
    $url = file_create_url($filepath);
2504
    $this->assertEqual(base_path() . '/' . $filepath, $url, 'Correctly generated a root-relative URL for a shipped file.');
2505

    
2506
    // Test alteration of file URLs to use protocol-relative URLs.
2507
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2508
    $filepath = 'misc/jquery.js';
2509
    $url = file_create_url($filepath);
2510
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2511
    $filepath = 'misc/favicon.ico';
2512
    $url = file_create_url($filepath);
2513
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2514
  }
2515

    
2516
  /**
2517
   * Test the generating of rewritten public created file URLs.
2518
   */
2519
  function testPublicCreatedFileURL() {
2520
    // Test generating an URL to a created file.
2521

    
2522
    // Test alteration of file URLs to use a CDN.
2523
    variable_set('file_test_hook_file_url_alter', 'cdn');
2524
    $file = $this->createFile();
2525
    $url = file_create_url($file->uri);
2526
    $public_directory_path = file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath();
2527
    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a CDN URL for a created file.');
2528

    
2529
    // Test alteration of file URLs to use root-relative URLs.
2530
    variable_set('file_test_hook_file_url_alter', 'root-relative');
2531
    $file = $this->createFile();
2532
    $url = file_create_url($file->uri);
2533
    $this->assertEqual(base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a root-relative URL for a created file.');
2534

    
2535
    // Test alteration of file URLs to use a protocol-relative URLs.
2536
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2537
    $file = $this->createFile();
2538
    $url = file_create_url($file->uri);
2539
    $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a protocol-relative URL for a created file.');
2540
  }
2541
}
2542

    
2543
/**
2544
 * Tests for file_munge_filename() and file_unmunge_filename().
2545
 */
2546
class FileNameMungingTest extends FileTestCase {
2547
  public static function getInfo() {
2548
    return array(
2549
      'name' => 'File naming',
2550
      'description' => 'Test filename munging and unmunging.',
2551
      'group' => 'File API',
2552
    );
2553
  }
2554

    
2555
  function setUp() {
2556
    parent::setUp();
2557
    $this->bad_extension = 'php';
2558
    $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
2559
    $this->name_with_uc_ext = $this->randomName() . '.' . strtoupper($this->bad_extension) . '.txt';
2560
  }
2561

    
2562
  /**
2563
   * Create a file and munge/unmunge the name.
2564
   */
2565
  function testMunging() {
2566
    // Disable insecure uploads.
2567
    variable_set('allow_insecure_uploads', 0);
2568
    $munged_name = file_munge_filename($this->name, '', TRUE);
2569
    $messages = drupal_get_messages();
2570
    $this->assertTrue(in_array(t('For security reasons, your upload has been renamed to %filename.', array('%filename' => $munged_name)), $messages['status']), 'Alert properly set when a file is renamed.');
2571
    $this->assertNotEqual($munged_name, $this->name, format_string('The new filename (%munged) has been modified from the original (%original)', array('%munged' => $munged_name, '%original' => $this->name)));
2572
  }
2573

    
2574
  /**
2575
   * Tests munging with a null byte in the filename.
2576
   */
2577
  function testMungeNullByte() {
2578
    $prefix = $this->randomName();
2579
    $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
2580
    $this->assertEqual(file_munge_filename($filename, ''), $prefix . '.' . $this->bad_extension . '_.txt', 'A filename with a null byte is correctly munged to remove the null byte.');
2581
  }
2582

    
2583
  /**
2584
   * If the allow_insecure_uploads variable evaluates to true, the file should
2585
   * come out untouched, no matter how evil the filename.
2586
   */
2587
  function testMungeIgnoreInsecure() {
2588
    variable_set('allow_insecure_uploads', 1);
2589
    $munged_name = file_munge_filename($this->name, '');
2590
    $this->assertIdentical($munged_name, $this->name, format_string('The original filename (%original) matches the munged filename (%munged) when insecure uploads are enabled.', array('%munged' => $munged_name, '%original' => $this->name)));
2591
  }
2592

    
2593
  /**
2594
   * White listed extensions are ignored by file_munge_filename().
2595
   */
2596
  function testMungeIgnoreWhitelisted() {
2597
    // Declare our extension as whitelisted. The declared extensions should
2598
    // be case insensitive so test using one with a different case.
2599
    $munged_name = file_munge_filename($this->name_with_uc_ext, $this->bad_extension);
2600
    $this->assertIdentical($munged_name, $this->name_with_uc_ext, format_string('The new filename (%munged) matches the original (%original) once the extension has been whitelisted.', array('%munged' => $munged_name, '%original' => $this->name_with_uc_ext)));
2601
    // The allowed extensions should also be normalized.
2602
    $munged_name = file_munge_filename($this->name, strtoupper($this->bad_extension));
2603
    $this->assertIdentical($munged_name, $this->name, format_string('The new filename (%munged) matches the original (%original) also when the whitelisted extension is in uppercase.', array('%munged' => $munged_name, '%original' => $this->name)));
2604
  }
2605

    
2606
  /**
2607
   * Ensure that unmunge gets your name back.
2608
   */
2609
  function testUnMunge() {
2610
    $munged_name = file_munge_filename($this->name, '', FALSE);
2611
    $unmunged_name = file_unmunge_filename($munged_name);
2612
    $this->assertIdentical($unmunged_name, $this->name, format_string('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
2613
  }
2614
}
2615

    
2616
/**
2617
 * Tests for file_get_mimetype().
2618
 */
2619
class FileMimeTypeTest extends DrupalWebTestCase {
2620
  function setUp() {
2621
    parent::setUp('file_test');
2622
  }
2623

    
2624
  public static function getInfo() {
2625
    return array(
2626
      'name' => 'File mimetypes',
2627
      'description' => 'Test filename mimetype detection.',
2628
      'group' => 'File API',
2629
    );
2630
  }
2631

    
2632
  /**
2633
   * Test mapping of mimetypes from filenames.
2634
   */
2635
  public function testFileMimeTypeDetection() {
2636
    $prefix = 'public://';
2637

    
2638
    $test_case = array(
2639
      'test.jar' => 'application/java-archive',
2640
      'test.jpeg' => 'image/jpeg',
2641
      'test.JPEG' => 'image/jpeg',
2642
      'test.jpg' => 'image/jpeg',
2643
      'test.jar.jpg' => 'image/jpeg',
2644
      'test.jpg.jar' => 'application/java-archive',
2645
      'test.pcf.Z' => 'application/x-font',
2646
      'pcf.z' => 'application/octet-stream',
2647
      'jar' => 'application/octet-stream',
2648
      'some.junk' => 'application/octet-stream',
2649
      'foo.file_test_1' => 'madeup/file_test_1',
2650
      'foo.file_test_2' => 'madeup/file_test_2',
2651
      'foo.doc' => 'madeup/doc',
2652
      'test.ogg' => 'audio/ogg',
2653
    );
2654

    
2655
    // Test using default mappings.
2656
    foreach ($test_case as $input => $expected) {
2657
      // Test stream [URI].
2658
      $output = file_get_mimetype($prefix . $input);
2659
      $this->assertIdentical($output, $expected, format_string('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2660

    
2661
      // Test normal path equivalent
2662
      $output = file_get_mimetype($input);
2663
      $this->assertIdentical($output, $expected, format_string('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2664
    }
2665

    
2666
    // Now test passing in the map.
2667
    $mapping = array(
2668
      'mimetypes' => array(
2669
        0 => 'application/java-archive',
2670
        1 => 'image/jpeg',
2671
      ),
2672
      'extensions' => array(
2673
         'jar' => 0,
2674
         'jpg' => 1,
2675
      )
2676
    );
2677

    
2678
    $test_case = array(
2679
      'test.jar' => 'application/java-archive',
2680
      'test.jpeg' => 'application/octet-stream',
2681
      'test.jpg' => 'image/jpeg',
2682
      'test.jar.jpg' => 'image/jpeg',
2683
      'test.jpg.jar' => 'application/java-archive',
2684
      'test.pcf.z' => 'application/octet-stream',
2685
      'pcf.z' => 'application/octet-stream',
2686
      'jar' => 'application/octet-stream',
2687
      'some.junk' => 'application/octet-stream',
2688
      'foo.file_test_1' => 'application/octet-stream',
2689
      'foo.file_test_2' => 'application/octet-stream',
2690
      'foo.doc' => 'application/octet-stream',
2691
      'test.ogg' => 'application/octet-stream',
2692
    );
2693

    
2694
    foreach ($test_case as $input => $expected) {
2695
      $output = file_get_mimetype($input, $mapping);
2696
      $this->assertIdentical($output, $expected, format_string('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2697
    }
2698
  }
2699
}
2700

    
2701
/**
2702
 * Tests stream wrapper functions.
2703
 */
2704
class StreamWrapperTest extends DrupalWebTestCase {
2705

    
2706
  protected $scheme = 'dummy';
2707
  protected $classname = 'DrupalDummyStreamWrapper';
2708

    
2709
  public static function getInfo() {
2710
    return array(
2711
      'name' => 'Stream wrappers',
2712
      'description' => 'Tests stream wrapper functions.',
2713
      'group' => 'File API',
2714
    );
2715
  }
2716

    
2717
  function setUp() {
2718
    parent::setUp('file_test');
2719
    drupal_static_reset('file_get_stream_wrappers');
2720
  }
2721

    
2722
  function tearDown() {
2723
    parent::tearDown();
2724
    stream_wrapper_unregister($this->scheme);
2725
  }
2726

    
2727
  /**
2728
   * Test the getClassName() function.
2729
   */
2730
  function testGetClassName() {
2731
    // Check the dummy scheme.
2732
    $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), 'Got correct class name for dummy scheme.');
2733
    // Check core's scheme.
2734
    $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), 'Got correct class name for public scheme.');
2735
  }
2736

    
2737
  /**
2738
   * Test the file_stream_wrapper_get_instance_by_scheme() function.
2739
   */
2740
  function testGetInstanceByScheme() {
2741
    $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
2742
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy scheme.');
2743

    
2744
    $instance = file_stream_wrapper_get_instance_by_scheme('public');
2745
    $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public scheme.');
2746
  }
2747

    
2748
  /**
2749
   * Test the URI and target functions.
2750
   */
2751
  function testUriFunctions() {
2752
    $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
2753
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
2754

    
2755
    $instance = file_stream_wrapper_get_instance_by_uri('public://foo');
2756
    $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public URI.');
2757

    
2758
    // Test file_uri_target().
2759
    $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
2760
    $this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
2761

    
2762
    // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
2763
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
2764
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), 'Expected default directory path was returned.');
2765
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), 'Expected temporary directory path was returned.');
2766

    
2767
    variable_set('file_default_scheme', 'private');
2768
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
2769
  }
2770

    
2771
  /**
2772
   * Test the scheme functions.
2773
   */
2774
  function testGetValidStreamScheme() {
2775
    $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
2776
    $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
2777
    $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
2778
  }
2779
}