Projet

Général

Profil

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

root / drupal7 / modules / simpletest / tests / file.test @ 27e02aed

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
    // Create a file with a size of 1000 bytes, and quotas of only 1 byte.
484
    $file = new stdClass();
485
    $file->filesize = 1000;
486
    $errors = file_validate_size($file, 0, 0);
487
    $this->assertEqual(count($errors), 0, 'No limits means no errors.', 'File');
488
    $errors = file_validate_size($file, 1, 0);
489
    $this->assertEqual(count($errors), 1, 'Error for the file being over the limit.', 'File');
490
    $errors = file_validate_size($file, 0, 1);
491
    $this->assertEqual(count($errors), 1, 'Error for the user being over their limit.', 'File');
492
    $errors = file_validate_size($file, 1, 1);
493
    $this->assertEqual(count($errors), 2, 'Errors for both the file and their limit.', 'File');
494
  }
495
}
496

    
497

    
498

    
499
/**
500
 *  Tests the file_unmanaged_save_data() function.
501
 */
502
class FileUnmanagedSaveDataTest extends FileTestCase {
503
  public static function getInfo() {
504
    return array(
505
      'name' => 'Unmanaged file save data',
506
      'description' => 'Tests the unmanaged file save data function.',
507
      'group' => 'File API',
508
    );
509
  }
510

    
511
  /**
512
   * Test the file_unmanaged_save_data() function.
513
   */
514
  function testFileSaveData() {
515
    $contents = $this->randomName(8);
516

    
517
    // No filename.
518
    $filepath = file_unmanaged_save_data($contents);
519
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
520
    $this->assertEqual(file_uri_scheme($filepath), file_default_scheme(), "File was placed in Drupal's files directory.");
521
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
522

    
523
    // Provide a filename.
524
    $filepath = file_unmanaged_save_data($contents, 'public://asdf.txt', FILE_EXISTS_REPLACE);
525
    $this->assertTrue($filepath, 'Unnamed file saved correctly.');
526
    $this->assertEqual('asdf.txt', drupal_basename($filepath), 'File was named correctly.');
527
    $this->assertEqual($contents, file_get_contents($filepath), 'Contents of the file are correct.');
528
    $this->assertFilePermissions($filepath, variable_get('file_chmod_file', 0664));
529
  }
530
}
531

    
532
/**
533
 *  Tests the file_unmanaged_save_data() function on remote filesystems.
534
 */
535
class RemoteFileUnmanagedSaveDataTest extends FileUnmanagedSaveDataTest {
536
  public static function getInfo() {
537
    $info = parent::getInfo();
538
    $info['group'] = 'File API (remote)';
539
    return $info;
540
  }
541

    
542
  function setUp() {
543
    parent::setUp('file_test');
544
    variable_set('file_default_scheme', 'dummy-remote');
545
  }
546
}
547

    
548
/**
549
 * Test the file_save_upload() function.
550
 */
551
class FileSaveUploadTest extends FileHookTestCase {
552
  /**
553
   * An image file path for uploading.
554
   */
555
  protected $image;
556

    
557
  /**
558
   * A PHP file path for upload security testing.
559
   */
560
  protected $phpfile;
561

    
562
  /**
563
   * The largest file id when the test starts.
564
   */
565
  protected $maxFidBefore;
566

    
567
  public static function getInfo() {
568
    return array(
569
      'name' => 'File uploading',
570
      'description' => 'Tests the file uploading functions.',
571
      'group' => 'File API',
572
    );
573
  }
574

    
575
  function setUp() {
576
    parent::setUp();
577
    $account = $this->drupalCreateUser(array('access content'));
578
    $this->drupalLogin($account);
579

    
580
    $image_files = $this->drupalGetTestFiles('image');
581
    $this->image = current($image_files);
582

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

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

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

    
591
    // Upload with replace to guarantee there's something there.
592
    $edit = array(
593
      'file_test_replace' => FILE_EXISTS_REPLACE,
594
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
595
    );
596
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
597
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
598
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
599

    
600
    // Check that the correct hooks were called then clean out the hook
601
    // counters.
602
    $this->assertFileHooksCalled(array('validate', 'insert'));
603
    file_test_reset();
604
  }
605

    
606
  /**
607
   * Test the file_save_upload() function.
608
   */
609
  function testNormal() {
610
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
611
    $this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
612
    $file1 = file_load($max_fid_after);
613
    $this->assertTrue($file1, 'Loaded the file.');
614
    // MIME type of the uploaded image may be either image/jpeg or image/png.
615
    $this->assertEqual(substr($file1->filemime, 0, 5), 'image', 'A MIME type was set.');
616

    
617
    // Reset the hook counters to get rid of the 'load' we just called.
618
    file_test_reset();
619

    
620
    // Upload a second file.
621
    $max_fid_before = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
622
    $image2 = current($this->drupalGetTestFiles('image'));
623
    $edit = array('files[file_test_upload]' => drupal_realpath($image2->uri));
624
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
625
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
626
    $this->assertRaw(t('You WIN!'));
627
    $max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
628

    
629
    // Check that the correct hooks were called.
630
    $this->assertFileHooksCalled(array('validate', 'insert'));
631

    
632
    $file2 = file_load($max_fid_after);
633
    $this->assertTrue($file2);
634
    // MIME type of the uploaded image may be either image/jpeg or image/png.
635
    $this->assertEqual(substr($file2->filemime, 0, 5), 'image', 'A MIME type was set.');
636

    
637
    // Load both files using file_load_multiple().
638
    $files = file_load_multiple(array($file1->fid, $file2->fid));
639
    $this->assertTrue(isset($files[$file1->fid]), 'File was loaded successfully');
640
    $this->assertTrue(isset($files[$file2->fid]), 'File was loaded successfully');
641

    
642
    // Upload a third file to a subdirectory.
643
    $image3 = current($this->drupalGetTestFiles('image'));
644
    $image3_realpath = drupal_realpath($image3->uri);
645
    $dir = $this->randomName();
646
    $edit = array(
647
      'files[file_test_upload]' => $image3_realpath,
648
      'file_subdir' => $dir,
649
    );
650
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
651
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
652
    $this->assertRaw(t('You WIN!'));
653
    $this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
654

    
655
    // Check that file_load_multiple() with no arguments returns FALSE.
656
    $this->assertFalse(file_load_multiple(), 'No files were loaded.');
657
  }
658

    
659
  /**
660
   * Test extension handling.
661
   */
662
  function testHandleExtension() {
663
    // The file being tested is a .gif which is in the default safe list
664
    // of extensions to allow when the extension validator isn't used. This is
665
    // implicitly tested at the testNormal() test. Here we tell
666
    // file_save_upload() to only allow ".foo".
667
    $extensions = 'foo';
668
    $edit = array(
669
      'file_test_replace' => FILE_EXISTS_REPLACE,
670
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
671
      'extensions' => $extensions,
672
    );
673

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

    
680
    // Check that the correct hooks were called.
681
    $this->assertFileHooksCalled(array('validate'));
682

    
683
    // Reset the hook counters.
684
    file_test_reset();
685

    
686
    $extensions = 'foo ' . $this->image_extension;
687
    // Now tell file_save_upload() to allow the extension of our test image.
688
    $edit = array(
689
      'file_test_replace' => FILE_EXISTS_REPLACE,
690
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
691
      'extensions' => $extensions,
692
    );
693

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

    
699
    // Check that the correct hooks were called.
700
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
701

    
702
    // Reset the hook counters.
703
    file_test_reset();
704

    
705
    // Now tell file_save_upload() to allow any extension.
706
    $edit = array(
707
      'file_test_replace' => FILE_EXISTS_REPLACE,
708
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
709
      'allow_all_extensions' => TRUE,
710
    );
711
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
712
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
713
    $this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
714
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
715

    
716
    // Check that the correct hooks were called.
717
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
718
  }
719

    
720
  /**
721
   * Test dangerous file handling.
722
   */
723
  function testHandleDangerousFile() {
724
    // Allow the .php extension and make sure it gets renamed to .txt for
725
    // safety. Also check to make sure its MIME type was changed.
726
    $edit = array(
727
      'file_test_replace' => FILE_EXISTS_REPLACE,
728
      'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
729
      'is_image_file' => FALSE,
730
      'extensions' => 'php',
731
    );
732

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

    
740
    // Check that the correct hooks were called.
741
    $this->assertFileHooksCalled(array('validate', 'insert'));
742

    
743
    // Ensure dangerous files are not renamed when insecure uploads is TRUE.
744
    // Turn on insecure uploads.
745
    variable_set('allow_insecure_uploads', 1);
746
    // Reset the hook counters.
747
    file_test_reset();
748

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

    
755
    // Check that the correct hooks were called.
756
    $this->assertFileHooksCalled(array('validate', 'insert'));
757

    
758
    // Turn off insecure uploads.
759
    variable_set('allow_insecure_uploads', 0);
760
  }
761

    
762
  /**
763
   * Test file munge handling.
764
   */
765
  function testHandleFileMunge() {
766
    // Ensure insecure uploads are disabled for this test.
767
    variable_set('allow_insecure_uploads', 0);
768
    $this->image = file_move($this->image, $this->image->uri . '.foo.' . $this->image_extension);
769

    
770
    // Reset the hook counters to get rid of the 'move' we just called.
771
    file_test_reset();
772

    
773
    $extensions = $this->image_extension;
774
    $edit = array(
775
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
776
      'extensions' => $extensions,
777
    );
778

    
779
    $munged_filename = $this->image->filename;
780
    $munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
781
    $munged_filename .= '_.' . $this->image_extension;
782

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

    
789
    // Check that the correct hooks were called.
790
    $this->assertFileHooksCalled(array('validate', 'insert'));
791

    
792
    // Ensure we don't munge files if we're allowing any extension.
793
    // Reset the hook counters.
794
    file_test_reset();
795

    
796
    $edit = array(
797
      'files[file_test_upload]' => drupal_realpath($this->image->uri),
798
      'allow_all_extensions' => TRUE,
799
    );
800

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

    
807
    // Check that the correct hooks were called.
808
    $this->assertFileHooksCalled(array('validate', 'insert'));
809
  }
810

    
811
  /**
812
   * Test renaming when uploading over a file that already exists.
813
   */
814
  function testExistingRename() {
815
    $edit = array(
816
      'file_test_replace' => FILE_EXISTS_RENAME,
817
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
818
    );
819
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
820
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
821
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
822

    
823
    // Check that the correct hooks were called.
824
    $this->assertFileHooksCalled(array('validate', 'insert'));
825
  }
826

    
827
  /**
828
   * Test replacement when uploading over a file that already exists.
829
   */
830
  function testExistingReplace() {
831
    $edit = array(
832
      'file_test_replace' => FILE_EXISTS_REPLACE,
833
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
834
    );
835
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
836
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
837
    $this->assertRaw(t('You WIN!'), 'Found the success message.');
838

    
839
    // Check that the correct hooks were called.
840
    $this->assertFileHooksCalled(array('validate', 'load', 'update'));
841
  }
842

    
843
  /**
844
   * Test for failure when uploading over a file that already exists.
845
   */
846
  function testExistingError() {
847
    $edit = array(
848
      'file_test_replace' => FILE_EXISTS_ERROR,
849
      'files[file_test_upload]' => drupal_realpath($this->image->uri)
850
    );
851
    $this->drupalPost('file-test/upload', $edit, t('Submit'));
852
    $this->assertResponse(200, 'Received a 200 response for posted test file.');
853
    $this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
854

    
855
    // Check that the no hooks were called while failing.
856
    $this->assertFileHooksCalled(array());
857
  }
858

    
859
  /**
860
   * Test for no failures when not uploading a file.
861
   */
862
  function testNoUpload() {
863
    $this->drupalPost('file-test/upload', array(), t('Submit'));
864
    $this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
865
  }
866
}
867

    
868
/**
869
 * Test the file_save_upload() function on remote filesystems.
870
 */
871
class RemoteFileSaveUploadTest extends FileSaveUploadTest {
872
  public static function getInfo() {
873
    $info = parent::getInfo();
874
    $info['group'] = 'File API (remote)';
875
    return $info;
876
  }
877

    
878
  function setUp() {
879
    parent::setUp('file_test');
880
    variable_set('file_default_scheme', 'dummy-remote');
881
  }
882
}
883

    
884
/**
885
 * Directory related tests.
886
 */
887
class FileDirectoryTest extends FileTestCase {
888
  public static function getInfo() {
889
    return array(
890
      'name' => 'File paths and directories',
891
      'description' => 'Tests operations dealing with directories.',
892
      'group' => 'File API',
893
    );
894
  }
895

    
896
  /**
897
   * Test directory handling functions.
898
   */
899
  function testFileCheckDirectoryHandling() {
900
    // A directory to operate on.
901
    $directory = file_default_scheme() . '://' . $this->randomName() . '/' . $this->randomName();
902
    $this->assertFalse(is_dir($directory), 'Directory does not exist prior to testing.');
903

    
904
    // Non-existent directory.
905
    $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for non-existing directory.', 'File');
906

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

    
910
    // Make sure directory actually exists.
911
    $this->assertTrue(is_dir($directory), 'Directory actually exists.', 'File');
912

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

    
919
      // Make directory read only.
920
      @drupal_chmod($directory, 0444);
921
      $this->assertFalse(file_prepare_directory($directory, 0), 'Error reported for a non-writeable directory.', 'File');
922

    
923
      // Test directory permission modification.
924
      $this->assertTrue(file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS), 'No error reported when making directory writeable.', 'File');
925
    }
926

    
927
    // Test that the directory has the correct permissions.
928
    $this->assertDirectoryPermissions($directory, variable_get('file_chmod_directory', 0775));
929

    
930
    // Remove .htaccess file to then test that it gets re-created.
931
    @drupal_unlink(file_default_scheme() . '://.htaccess');
932
    $this->assertFalse(is_file(file_default_scheme() . '://.htaccess'), 'Successfully removed the .htaccess file in the files directory.', 'File');
933
    file_ensure_htaccess();
934
    $this->assertTrue(is_file(file_default_scheme() . '://.htaccess'), 'Successfully re-created the .htaccess file in the files directory.', 'File');
935
    // Verify contents of .htaccess file.
936
    $file = file_get_contents(file_default_scheme() . '://.htaccess');
937
    $this->assertEqual($file, file_htaccess_lines(FALSE), 'The .htaccess file contains the proper content.', 'File');
938
  }
939

    
940
  /**
941
   * This will take a directory and path, and find a valid filepath that is not
942
   * taken by another file.
943
   */
944
  function testFileCreateNewFilepath() {
945
    // First we test against an imaginary file that does not exist in a
946
    // directory.
947
    $basename = 'xyz.txt';
948
    $directory = 'misc';
949
    $original = $directory . '/' . $basename;
950
    $path = file_create_filename($basename, $directory);
951
    $this->assertEqual($path, $original, format_string('New filepath %new equals %original.', array('%new' => $path, '%original' => $original)), 'File');
952

    
953
    // Then we test against a file that already exists within that directory.
954
    $basename = 'druplicon.png';
955
    $original = $directory . '/' . $basename;
956
    $expected = $directory . '/druplicon_0.png';
957
    $path = file_create_filename($basename, $directory);
958
    $this->assertEqual($path, $expected, format_string('Creating a new filepath from %original equals %new.', array('%new' => $path, '%original' => $original)), 'File');
959

    
960
    try {
961
      $filename = "a\xFFtest\x80€.txt";
962
      file_create_filename($filename, $directory);
963
      $this->fail('Expected exception not thrown');
964
    }
965
    catch (RuntimeException $e) {
966
      $this->assertEqual("Invalid filename '$filename'", $e->getMessage(), 'The invalid filename has been detected and RuntimeException has been thrown.');
967
    }
968

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

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

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

    
1002
    try {
1003
      file_destination("core/misc/a\xFFtest\x80€.txt", FILE_EXISTS_REPLACE);
1004
      $this->fail('Expected exception not thrown');
1005
    }
1006
    catch (RuntimeException $e) {
1007
      $this->assertEqual("Invalid filename 'a\xFFtest\x80€.txt'", $e->getMessage(), 'The invalid destination has been detected and RuntimeException has been thrown.');
1008
    }
1009
  }
1010

    
1011
  /**
1012
   * Ensure that the file_directory_temp() function always returns a value.
1013
   */
1014
  function testFileDirectoryTemp() {
1015
    // Start with an empty variable to ensure we have a clean slate.
1016
    variable_set('file_temporary_path', '');
1017
    $tmp_directory = file_directory_temp();
1018
    $this->assertEqual(empty($tmp_directory), FALSE, 'file_directory_temp() returned a non-empty value.');
1019
    $setting = variable_get('file_temporary_path', '');
1020
    $this->assertEqual($setting, $tmp_directory, "The 'file_temporary_path' variable has the same value that file_directory_temp() returned.");
1021
  }
1022
}
1023

    
1024
/**
1025
 * Directory related tests.
1026
 */
1027
class RemoteFileDirectoryTest extends FileDirectoryTest {
1028
  public static function getInfo() {
1029
    $info = parent::getInfo();
1030
    $info['group'] = 'File API (remote)';
1031
    return $info;
1032
  }
1033

    
1034
  function setUp() {
1035
    parent::setUp('file_test');
1036
    variable_set('file_default_scheme', 'dummy-remote');
1037
  }
1038
}
1039

    
1040
/**
1041
 * Tests the file_scan_directory() function.
1042
 */
1043
class FileScanDirectoryTest extends FileTestCase {
1044
  public static function getInfo() {
1045
    return array(
1046
      'name' => 'File scan directory',
1047
      'description' => 'Tests the file_scan_directory() function.',
1048
      'group' => 'File API',
1049
    );
1050
  }
1051

    
1052
  function setUp() {
1053
    parent::setUp();
1054
    $this->path = drupal_get_path('module', 'simpletest') . '/files';
1055
  }
1056

    
1057
  /**
1058
   * Check the format of the returned values.
1059
   */
1060
  function testReturn() {
1061
    // Grab a listing of all the JavaSscript files and check that they're
1062
    // passed to the callback.
1063
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1064
    ksort($all_files);
1065
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1066

    
1067
    // Check the first file.
1068
    $file = reset($all_files);
1069
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the first returned file.');
1070
    $this->assertEqual($file->uri, $this->path . '/javascript-1.txt', 'First file name was set correctly.');
1071
    $this->assertEqual($file->filename, 'javascript-1.txt', 'First basename was set correctly');
1072
    $this->assertEqual($file->name, 'javascript-1', 'First name was set correctly.');
1073

    
1074
    // Check the second file.
1075
    $file = next($all_files);
1076
    $this->assertEqual(key($all_files), $file->uri, 'Correct array key was used for the second returned file.');
1077
    $this->assertEqual($file->uri, $this->path . '/javascript-2.script', 'Second file name was set correctly.');
1078
    $this->assertEqual($file->filename, 'javascript-2.script', 'Second basename was set correctly');
1079
    $this->assertEqual($file->name, 'javascript-2', 'Second name was set correctly.');
1080
  }
1081

    
1082
  /**
1083
   * Check that the callback function is called correctly.
1084
   */
1085
  function testOptionCallback() {
1086
    // When nothing is matched nothing should be passed to the callback.
1087
    $all_files = file_scan_directory($this->path, '/^NONEXISTINGFILENAME/', array('callback' => 'file_test_file_scan_callback'));
1088
    $this->assertEqual(0, count($all_files), 'No files were found.');
1089
    $results = file_test_file_scan_callback();
1090
    file_test_file_scan_callback_reset();
1091
    $this->assertEqual(0, count($results), 'No files were passed to the callback.');
1092

    
1093
    // Grab a listing of all the JavaSscript files and check that they're
1094
    // passed to the callback.
1095
    $all_files = file_scan_directory($this->path, '/^javascript-/', array('callback' => 'file_test_file_scan_callback'));
1096
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1097
    $results = file_test_file_scan_callback();
1098
    file_test_file_scan_callback_reset();
1099
    $this->assertEqual(2, count($results), 'Files were passed to the callback.');
1100
  }
1101

    
1102
  /**
1103
   * Check that the no-mask parameter is honored.
1104
   */
1105
  function testOptionNoMask() {
1106
    // Grab a listing of all the JavaSscript files.
1107
    $all_files = file_scan_directory($this->path, '/^javascript-/');
1108
    $this->assertEqual(2, count($all_files), 'Found two, expected javascript files.');
1109

    
1110
    // Now use the nomast parameter to filter out the .script file.
1111
    $filtered_files = file_scan_directory($this->path, '/^javascript-/', array('nomask' => '/.script$/'));
1112
    $this->assertEqual(1, count($filtered_files), 'Filtered correctly.');
1113
  }
1114

    
1115
  /**
1116
   * Check that key parameter sets the return value's key.
1117
   */
1118
  function testOptionKey() {
1119
    // "filename", for the path starting with $dir.
1120
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1121
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filepath')));
1122
    sort($actual);
1123
    $this->assertEqual($expected, $actual, 'Returned the correct values for the filename key.');
1124

    
1125
    // "basename", for the basename of the file.
1126
    $expected = array('javascript-1.txt', 'javascript-2.script');
1127
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'filename')));
1128
    sort($actual);
1129
    $this->assertEqual($expected, $actual, 'Returned the correct values for the basename key.');
1130

    
1131
    // "name" for the name of the file without an extension.
1132
    $expected = array('javascript-1', 'javascript-2');
1133
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'name')));
1134
    sort($actual);
1135
    $this->assertEqual($expected, $actual, 'Returned the correct values for the name key.');
1136

    
1137
    // Invalid option that should default back to "filename".
1138
    $expected = array($this->path . '/javascript-1.txt', $this->path . '/javascript-2.script');
1139
    $actual = array_keys(file_scan_directory($this->path, '/^javascript-/', array('key' => 'INVALID')));
1140
    sort($actual);
1141
    $this->assertEqual($expected, $actual, 'An invalid key defaulted back to the default.');
1142
  }
1143

    
1144
  /**
1145
   * Check that the recurse option decends into subdirectories.
1146
   */
1147
  function testOptionRecurse() {
1148
    $files = file_scan_directory(drupal_get_path('module', 'simpletest'), '/^javascript-/', array('recurse' => FALSE));
1149
    $this->assertTrue(empty($files), "Without recursion couldn't find javascript files.");
1150

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

    
1155

    
1156
  /**
1157
   * Check that the min_depth options lets us ignore files in the starting
1158
   * directory.
1159
   */
1160
  function testOptionMinDepth() {
1161
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 0));
1162
    $this->assertEqual(2, count($files), 'No minimum-depth gets files in current directory.');
1163

    
1164
    $files = file_scan_directory($this->path, '/^javascript-/', array('min_depth' => 1));
1165
    $this->assertTrue(empty($files), "Minimum-depth of 1 successfully excludes files from current directory.");
1166
  }
1167
}
1168

    
1169
/**
1170
 * Tests the file_scan_directory() function on remote filesystems.
1171
 */
1172
class RemoteFileScanDirectoryTest extends FileScanDirectoryTest {
1173
  public static function getInfo() {
1174
    $info = parent::getInfo();
1175
    $info['group'] = 'File API (remote)';
1176
    return $info;
1177
  }
1178

    
1179
  function setUp() {
1180
    parent::setUp('file_test');
1181
    variable_set('file_default_scheme', 'dummy-remote');
1182
  }
1183
}
1184

    
1185
/**
1186
 * Deletion related tests.
1187
 */
1188
class FileUnmanagedDeleteTest extends FileTestCase {
1189
  public static function getInfo() {
1190
    return array(
1191
      'name' => 'Unmanaged file delete',
1192
      'description' => 'Tests the unmanaged file delete function.',
1193
      'group' => 'File API',
1194
    );
1195
  }
1196

    
1197
  /**
1198
   * Delete a normal file.
1199
   */
1200
  function testNormal() {
1201
    // Create a file for testing
1202
    $file = $this->createFile();
1203

    
1204
    // Delete a regular file
1205
    $this->assertTrue(file_unmanaged_delete($file->uri), 'Deleted worked.');
1206
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1207
  }
1208

    
1209
  /**
1210
   * Try deleting a missing file.
1211
   */
1212
  function testMissing() {
1213
    // Try to delete a non-existing file
1214
    $this->assertTrue(file_unmanaged_delete(file_default_scheme() . '/' . $this->randomName()), 'Returns true when deleting a non-existent file.');
1215
  }
1216

    
1217
  /**
1218
   * Try deleting a directory.
1219
   */
1220
  function testDirectory() {
1221
    // A directory to operate on.
1222
    $directory = $this->createDirectory();
1223

    
1224
    // Try to delete a directory
1225
    $this->assertFalse(file_unmanaged_delete($directory), 'Could not delete the delete directory.');
1226
    $this->assertTrue(file_exists($directory), 'Directory has not been deleted.');
1227
  }
1228
}
1229

    
1230
/**
1231
 * Deletion related tests on remote filesystems.
1232
 */
1233
class RemoteFileUnmanagedDeleteTest extends FileUnmanagedDeleteTest {
1234
  public static function getInfo() {
1235
    $info = parent::getInfo();
1236
    $info['group'] = 'File API (remote)';
1237
    return $info;
1238
  }
1239

    
1240
  function setUp() {
1241
    parent::setUp('file_test');
1242
    variable_set('file_default_scheme', 'dummy-remote');
1243
  }
1244
}
1245

    
1246
/**
1247
 * Deletion related tests.
1248
 */
1249
class FileUnmanagedDeleteRecursiveTest extends FileTestCase {
1250
  public static function getInfo() {
1251
    return array(
1252
      'name' => 'Unmanaged recursive file delete',
1253
      'description' => 'Tests the unmanaged file delete recursive function.',
1254
      'group' => 'File API',
1255
    );
1256
  }
1257

    
1258
  /**
1259
   * Delete a normal file.
1260
   */
1261
  function testSingleFile() {
1262
    // Create a file for testing
1263
    $filepath = file_default_scheme() . '://' . $this->randomName();
1264
    file_put_contents($filepath, '');
1265

    
1266
    // Delete the file.
1267
    $this->assertTrue(file_unmanaged_delete_recursive($filepath), 'Function reported success.');
1268
    $this->assertFalse(file_exists($filepath), 'Test file has been deleted.');
1269
  }
1270

    
1271
  /**
1272
   * Try deleting an empty directory.
1273
   */
1274
  function testEmptyDirectory() {
1275
    // A directory to operate on.
1276
    $directory = $this->createDirectory();
1277

    
1278
    // Delete the directory.
1279
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1280
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1281
  }
1282

    
1283
  /**
1284
   * Try deleting a directory with some files.
1285
   */
1286
  function testDirectory() {
1287
    // A directory to operate on.
1288
    $directory = $this->createDirectory();
1289
    $filepathA = $directory . '/A';
1290
    $filepathB = $directory . '/B';
1291
    file_put_contents($filepathA, '');
1292
    file_put_contents($filepathB, '');
1293

    
1294
    // Delete the directory.
1295
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1296
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1297
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1298
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1299
  }
1300

    
1301
  /**
1302
   * Try deleting subdirectories with some files.
1303
   */
1304
  function testSubDirectory() {
1305
    // A directory to operate on.
1306
    $directory = $this->createDirectory();
1307
    $subdirectory = $this->createDirectory($directory . '/sub');
1308
    $filepathA = $directory . '/A';
1309
    $filepathB = $subdirectory . '/B';
1310
    file_put_contents($filepathA, '');
1311
    file_put_contents($filepathB, '');
1312

    
1313
    // Delete the directory.
1314
    $this->assertTrue(file_unmanaged_delete_recursive($directory), 'Function reported success.');
1315
    $this->assertFalse(file_exists($filepathA), 'Test file A has been deleted.');
1316
    $this->assertFalse(file_exists($filepathB), 'Test file B has been deleted.');
1317
    $this->assertFalse(file_exists($subdirectory), 'Subdirectory has been deleted.');
1318
    $this->assertFalse(file_exists($directory), 'Directory has been deleted.');
1319
  }
1320
}
1321

    
1322
/**
1323
 * Deletion related tests on remote filesystems.
1324
 */
1325
class RemoteFileUnmanagedDeleteRecursiveTest extends FileUnmanagedDeleteRecursiveTest {
1326
  public static function getInfo() {
1327
    $info = parent::getInfo();
1328
    $info['group'] = 'File API (remote)';
1329
    return $info;
1330
  }
1331

    
1332
  function setUp() {
1333
    parent::setUp('file_test');
1334
    variable_set('file_default_scheme', 'dummy-remote');
1335
  }
1336
}
1337

    
1338
/**
1339
 * Unmanaged move related tests.
1340
 */
1341
class FileUnmanagedMoveTest extends FileTestCase {
1342
  public static function getInfo() {
1343
    return array(
1344
      'name' => 'Unmanaged file moving',
1345
      'description' => 'Tests the unmanaged file move function.',
1346
      'group' => 'File API',
1347
    );
1348
  }
1349

    
1350
  /**
1351
   * Move a normal file.
1352
   */
1353
  function testNormal() {
1354
    // Create a file for testing
1355
    $file = $this->createFile();
1356

    
1357
    // Moving to a new name.
1358
    $desired_filepath = 'public://' . $this->randomName();
1359
    $new_filepath = file_unmanaged_move($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1360
    $this->assertTrue($new_filepath, 'Move was successful.');
1361
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1362
    $this->assertTrue(file_exists($new_filepath), 'File exists at the new location.');
1363
    $this->assertFalse(file_exists($file->uri), 'No file remains at the old location.');
1364
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1365

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

    
1377
    // TODO: test moving to a directory (rather than full directory/file path)
1378
    // TODO: test creating and moving normal files (rather than streams)
1379
  }
1380

    
1381
  /**
1382
   * Try to move a missing file.
1383
   */
1384
  function testMissing() {
1385
    // Move non-existent file.
1386
    $new_filepath = file_unmanaged_move($this->randomName(), $this->randomName());
1387
    $this->assertFalse($new_filepath, 'Moving a missing file fails.');
1388
  }
1389

    
1390
  /**
1391
   * Try to move a file onto itself.
1392
   */
1393
  function testOverwriteSelf() {
1394
    // Create a file for testing.
1395
    $file = $this->createFile();
1396

    
1397
    // Move the file onto itself without renaming shouldn't make changes.
1398
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_REPLACE);
1399
    $this->assertFalse($new_filepath, 'Moving onto itself without renaming fails.');
1400
    $this->assertTrue(file_exists($file->uri), 'File exists after moving onto itself.');
1401

    
1402
    // Move the file onto itself with renaming will result in a new filename.
1403
    $new_filepath = file_unmanaged_move($file->uri, $file->uri, FILE_EXISTS_RENAME);
1404
    $this->assertTrue($new_filepath, 'Moving onto itself with renaming works.');
1405
    $this->assertFalse(file_exists($file->uri), 'Original file has been removed.');
1406
    $this->assertTrue(file_exists($new_filepath), 'File exists after moving onto itself.');
1407
  }
1408
}
1409

    
1410
/**
1411
 * Unmanaged move related tests on remote filesystems.
1412
 */
1413
class RemoteFileUnmanagedMoveTest extends FileUnmanagedMoveTest {
1414
  public static function getInfo() {
1415
    $info = parent::getInfo();
1416
    $info['group'] = 'File API (remote)';
1417
    return $info;
1418
  }
1419

    
1420
  function setUp() {
1421
    parent::setUp('file_test');
1422
    variable_set('file_default_scheme', 'dummy-remote');
1423
  }
1424
}
1425

    
1426
/**
1427
 * Unmanaged copy related tests.
1428
 */
1429
class FileUnmanagedCopyTest extends FileTestCase {
1430
  public static function getInfo() {
1431
    return array(
1432
      'name' => 'Unmanaged file copying',
1433
      'description' => 'Tests the unmanaged file copy function.',
1434
      'group' => 'File API',
1435
    );
1436
  }
1437

    
1438
  /**
1439
   * Copy a normal file.
1440
   */
1441
  function testNormal() {
1442
    // Create a file for testing
1443
    $file = $this->createFile();
1444

    
1445
    // Copying to a new name.
1446
    $desired_filepath = 'public://' . $this->randomName();
1447
    $new_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_ERROR);
1448
    $this->assertTrue($new_filepath, 'Copy was successful.');
1449
    $this->assertEqual($new_filepath, $desired_filepath, 'Returned expected filepath.');
1450
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1451
    $this->assertTrue(file_exists($new_filepath), 'New file exists.');
1452
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1453

    
1454
    // Copying with rename.
1455
    $desired_filepath = 'public://' . $this->randomName();
1456
    $this->assertTrue(file_put_contents($desired_filepath, ' '), 'Created a file so a rename will have to happen.');
1457
    $newer_filepath = file_unmanaged_copy($file->uri, $desired_filepath, FILE_EXISTS_RENAME);
1458
    $this->assertTrue($newer_filepath, 'Copy was successful.');
1459
    $this->assertNotEqual($newer_filepath, $desired_filepath, 'Returned expected filepath.');
1460
    $this->assertTrue(file_exists($file->uri), 'Original file remains.');
1461
    $this->assertTrue(file_exists($newer_filepath), 'New file exists.');
1462
    $this->assertFilePermissions($newer_filepath, variable_get('file_chmod_file', 0664));
1463

    
1464
    // TODO: test copying to a directory (rather than full directory/file path)
1465
    // TODO: test copying normal files using normal paths (rather than only streams)
1466
  }
1467

    
1468
  /**
1469
   * Copy a non-existent file.
1470
   */
1471
  function testNonExistent() {
1472
    // Copy non-existent file
1473
    $desired_filepath = $this->randomName();
1474
    $this->assertFalse(file_exists($desired_filepath), "Randomly named file doesn't exists.");
1475
    $new_filepath = file_unmanaged_copy($desired_filepath, $this->randomName());
1476
    $this->assertFalse($new_filepath, 'Copying a missing file fails.');
1477
  }
1478

    
1479
  /**
1480
   * Copy a file onto itself.
1481
   */
1482
  function testOverwriteSelf() {
1483
    // Create a file for testing
1484
    $file = $this->createFile();
1485

    
1486
    // Copy the file onto itself with renaming works.
1487
    $new_filepath = file_unmanaged_copy($file->uri, $file->uri, FILE_EXISTS_RENAME);
1488
    $this->assertTrue($new_filepath, 'Copying onto itself with renaming works.');
1489
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1490
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1491
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1492
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1493

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

    
1499
    // Copy the file into same directory without renaming fails.
1500
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_ERROR);
1501
    $this->assertFalse($new_filepath, 'Copying onto itself fails.');
1502
    $this->assertTrue(file_exists($file->uri), 'File exists after copying onto itself.');
1503

    
1504
    // Copy the file into same directory with renaming works.
1505
    $new_filepath = file_unmanaged_copy($file->uri, drupal_dirname($file->uri), FILE_EXISTS_RENAME);
1506
    $this->assertTrue($new_filepath, 'Copying into same directory works.');
1507
    $this->assertNotEqual($new_filepath, $file->uri, 'Copied file has a new name.');
1508
    $this->assertTrue(file_exists($file->uri), 'Original file exists after copying onto itself.');
1509
    $this->assertTrue(file_exists($new_filepath), 'Copied file exists after copying onto itself.');
1510
    $this->assertFilePermissions($new_filepath, variable_get('file_chmod_file', 0664));
1511
  }
1512
}
1513

    
1514
/**
1515
 * Unmanaged copy related tests on remote filesystems.
1516
 */
1517
class RemoteFileUnmanagedCopyTest extends FileUnmanagedCopyTest {
1518
  public static function getInfo() {
1519
    $info = parent::getInfo();
1520
    $info['group'] = 'File API (remote)';
1521
    return $info;
1522
  }
1523

    
1524
  function setUp() {
1525
    parent::setUp('file_test');
1526
    variable_set('file_default_scheme', 'dummy-remote');
1527
  }
1528
}
1529

    
1530
/**
1531
 * Deletion related tests.
1532
 */
1533
class FileDeleteTest extends FileHookTestCase {
1534
  public static function getInfo() {
1535
    return array(
1536
      'name' => 'File delete',
1537
      'description' => 'Tests the file delete function.',
1538
      'group' => 'File API',
1539
    );
1540
  }
1541

    
1542
  /**
1543
   * Tries deleting a normal file (as opposed to a directory, symlink, etc).
1544
   */
1545
  function testUnused() {
1546
    $file = $this->createFile();
1547

    
1548
    // Check that deletion removes the file and database record.
1549
    $this->assertTrue(is_file($file->uri), 'File exists.');
1550
    $this->assertIdentical(file_delete($file), TRUE, 'Delete worked.');
1551
    $this->assertFileHooksCalled(array('delete'));
1552
    $this->assertFalse(file_exists($file->uri), 'Test file has actually been deleted.');
1553
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1554
  }
1555

    
1556
  /**
1557
   * Tries deleting a file that is in use.
1558
   */
1559
  function testInUse() {
1560
    $file = $this->createFile();
1561
    file_usage_add($file, 'testing', 'test', 1);
1562
    file_usage_add($file, 'testing', 'test', 1);
1563

    
1564
    file_usage_delete($file, 'testing', 'test', 1);
1565
    file_delete($file);
1566
    $usage = file_usage_list($file);
1567
    $this->assertEqual($usage['testing']['test'], array(1 => 1), 'Test file is still in use.');
1568
    $this->assertTrue(file_exists($file->uri), 'File still exists on the disk.');
1569
    $this->assertTrue(file_load($file->fid), 'File still exists in the database.');
1570

    
1571
    // Clear out the call to hook_file_load().
1572
    file_test_reset();
1573

    
1574
    file_usage_delete($file, 'testing', 'test', 1);
1575
    file_delete($file);
1576
    $usage = file_usage_list($file);
1577
    $this->assertFileHooksCalled(array('delete'));
1578
    $this->assertTrue(empty($usage), 'File usage data was removed.');
1579
    $this->assertFalse(file_exists($file->uri), 'File has been deleted after its last usage was removed.');
1580
    $this->assertFalse(file_load($file->fid), 'File was removed from the database.');
1581
  }
1582
}
1583

    
1584

    
1585
/**
1586
 * Move related tests
1587
 */
1588
class FileMoveTest extends FileHookTestCase {
1589
  public static function getInfo() {
1590
    return array(
1591
      'name' => 'File moving',
1592
      'description' => 'Tests the file move function.',
1593
      'group' => 'File API',
1594
    );
1595
  }
1596

    
1597
  /**
1598
   * Move a normal file.
1599
   */
1600
  function testNormal() {
1601
    $contents = $this->randomName(10);
1602
    $source = $this->createFile(NULL, $contents);
1603
    $desired_filepath = 'public://' . $this->randomName();
1604

    
1605
    // Clone the object so we don't have to worry about the function changing
1606
    // our reference copy.
1607
    $result = file_move(clone $source, $desired_filepath, FILE_EXISTS_ERROR);
1608

    
1609
    // Check the return status and that the contents changed.
1610
    $this->assertTrue($result, 'File moved successfully.');
1611
    $this->assertFalse(file_exists($source->uri));
1612
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1613

    
1614
    // Check that the correct hooks were called.
1615
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1616

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

    
1620
    // Reload the file from the database and check that the changes were
1621
    // actually saved.
1622
    $loaded_file = file_load($result->fid, TRUE);
1623
    $this->assertTrue($loaded_file, 'File can be loaded from the database.');
1624
    $this->assertFileUnchanged($result, $loaded_file);
1625
  }
1626

    
1627
  /**
1628
   * Test renaming when moving onto a file that already exists.
1629
   */
1630
  function testExistingRename() {
1631
    // Setup a file to overwrite.
1632
    $contents = $this->randomName(10);
1633
    $source = $this->createFile(NULL, $contents);
1634
    $target = $this->createFile();
1635
    $this->assertDifferentFile($source, $target);
1636

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

    
1641
    // Check the return status and that the contents changed.
1642
    $this->assertTrue($result, 'File moved successfully.');
1643
    $this->assertFalse(file_exists($source->uri));
1644
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file correctly written.');
1645

    
1646
    // Check that the correct hooks were called.
1647
    $this->assertFileHooksCalled(array('move', 'load', 'update'));
1648

    
1649
    // Compare the returned value to what made it into the database.
1650
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1651
    // The target file should not have been altered.
1652
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1653
    // Make sure we end up with two distinct files afterwards.
1654
    $this->assertDifferentFile($target, $result);
1655

    
1656
    // Compare the source and results.
1657
    $loaded_source = file_load($source->fid, TRUE);
1658
    $this->assertEqual($loaded_source->fid, $result->fid, "Returned file's id matches the source.");
1659
    $this->assertNotEqual($loaded_source->uri, $source->uri, 'Returned file path has changed from the original.');
1660
  }
1661

    
1662
  /**
1663
   * Test replacement when moving onto a file that already exists.
1664
   */
1665
  function testExistingReplace() {
1666
    // Setup a file to overwrite.
1667
    $contents = $this->randomName(10);
1668
    $source = $this->createFile(NULL, $contents);
1669
    $target = $this->createFile();
1670
    $this->assertDifferentFile($source, $target);
1671

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

    
1676
    // Look at the results.
1677
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
1678
    $this->assertFalse(file_exists($source->uri));
1679
    $this->assertTrue($result, 'File moved successfully.');
1680

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

    
1684
    // Reload the file from the database and check that the changes were
1685
    // actually saved.
1686
    $loaded_result = file_load($result->fid, TRUE);
1687
    $this->assertFileUnchanged($result, $loaded_result);
1688
    // Check that target was re-used.
1689
    $this->assertSameFile($target, $loaded_result);
1690
    // Source and result should be totally different.
1691
    $this->assertDifferentFile($source, $loaded_result);
1692
  }
1693

    
1694
  /**
1695
   * Test replacement when moving onto itself.
1696
   */
1697
  function testExistingReplaceSelf() {
1698
    // Setup a file to overwrite.
1699
    $contents = $this->randomName(10);
1700
    $source = $this->createFile(NULL, $contents);
1701

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

    
1708
    // Check that no hooks were called while failing.
1709
    $this->assertFileHooksCalled(array());
1710

    
1711
    // Load the file from the database and make sure it is identical to what
1712
    // was returned.
1713
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1714
  }
1715

    
1716
  /**
1717
   * Test that moving onto an existing file fails when FILE_EXISTS_ERROR is
1718
   * specified.
1719
   */
1720
  function testExistingError() {
1721
    $contents = $this->randomName(10);
1722
    $source = $this->createFile();
1723
    $target = $this->createFile(NULL, $contents);
1724
    $this->assertDifferentFile($source, $target);
1725

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

    
1730
    // Check the return status and that the contents did not change.
1731
    $this->assertFalse($result, 'File move failed.');
1732
    $this->assertTrue(file_exists($source->uri));
1733
    $this->assertEqual($contents, file_get_contents($target->uri), 'Contents of file were not altered.');
1734

    
1735
    // Check that no hooks were called while failing.
1736
    $this->assertFileHooksCalled(array());
1737

    
1738
    // Load the file from the database and make sure it is identical to what
1739
    // was returned.
1740
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1741
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1742
  }
1743
}
1744

    
1745

    
1746
/**
1747
 * Copy related tests.
1748
 */
1749
class FileCopyTest extends FileHookTestCase {
1750
  public static function getInfo() {
1751
    return array(
1752
      'name' => 'File copying',
1753
      'description' => 'Tests the file copy function.',
1754
      'group' => 'File API',
1755
    );
1756
  }
1757

    
1758
  /**
1759
   * Test file copying in the normal, base case.
1760
   */
1761
  function testNormal() {
1762
    $contents = $this->randomName(10);
1763
    $source = $this->createFile(NULL, $contents);
1764
    $desired_uri = 'public://' . $this->randomName();
1765

    
1766
    // Clone the object so we don't have to worry about the function changing
1767
    // our reference copy.
1768
    $result = file_copy(clone $source, $desired_uri, FILE_EXISTS_ERROR);
1769

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

    
1774
    // Check that the correct hooks were called.
1775
    $this->assertFileHooksCalled(array('copy', 'insert'));
1776

    
1777
    $this->assertDifferentFile($source, $result);
1778
    $this->assertEqual($result->uri, $desired_uri, 'The copied file object has the desired filepath.');
1779
    $this->assertTrue(file_exists($source->uri), 'The original file still exists.');
1780
    $this->assertTrue(file_exists($result->uri), 'The copied file exists.');
1781

    
1782
    // Reload the file from the database and check that the changes were
1783
    // actually saved.
1784
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
1785
  }
1786

    
1787
  /**
1788
   * Test renaming when copying over a file that already exists.
1789
   */
1790
  function testExistingRename() {
1791
    // Setup a file to overwrite.
1792
    $contents = $this->randomName(10);
1793
    $source = $this->createFile(NULL, $contents);
1794
    $target = $this->createFile();
1795
    $this->assertDifferentFile($source, $target);
1796

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

    
1801
    // Check the return status and that the contents changed.
1802
    $this->assertTrue($result, 'File copied successfully.');
1803
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were copied correctly.');
1804
    $this->assertNotEqual($result->uri, $source->uri, 'Returned file path has changed from the original.');
1805

    
1806
    // Check that the correct hooks were called.
1807
    $this->assertFileHooksCalled(array('copy', 'insert'));
1808

    
1809
    // Load all the affected files to check the changes that actually made it
1810
    // to the database.
1811
    $loaded_source = file_load($source->fid, TRUE);
1812
    $loaded_target = file_load($target->fid, TRUE);
1813
    $loaded_result = file_load($result->fid, TRUE);
1814

    
1815
    // Verify that the source file wasn't changed.
1816
    $this->assertFileUnchanged($source, $loaded_source);
1817

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

    
1821
    // Make sure we end up with three distinct files afterwards.
1822
    $this->assertDifferentFile($loaded_source, $loaded_target);
1823
    $this->assertDifferentFile($loaded_target, $loaded_result);
1824
    $this->assertDifferentFile($loaded_source, $loaded_result);
1825
  }
1826

    
1827
  /**
1828
   * Test replacement when copying over a file that already exists.
1829
   */
1830
  function testExistingReplace() {
1831
    // Setup a file to overwrite.
1832
    $contents = $this->randomName(10);
1833
    $source = $this->createFile(NULL, $contents);
1834
    $target = $this->createFile();
1835
    $this->assertDifferentFile($source, $target);
1836

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

    
1841
    // Check the return status and that the contents changed.
1842
    $this->assertTrue($result, 'File copied successfully.');
1843
    $this->assertEqual($contents, file_get_contents($result->uri), 'Contents of file were overwritten.');
1844
    $this->assertDifferentFile($source, $result);
1845

    
1846
    // Check that the correct hooks were called.
1847
    $this->assertFileHooksCalled(array('load', 'copy', 'update'));
1848

    
1849
    // Load all the affected files to check the changes that actually made it
1850
    // to the database.
1851
    $loaded_source = file_load($source->fid, TRUE);
1852
    $loaded_target = file_load($target->fid, TRUE);
1853
    $loaded_result = file_load($result->fid, TRUE);
1854

    
1855
    // Verify that the source file wasn't changed.
1856
    $this->assertFileUnchanged($source, $loaded_source);
1857

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

    
1861
    // Target file was reused for the result.
1862
    $this->assertFileUnchanged($loaded_target, $loaded_result);
1863
  }
1864

    
1865
  /**
1866
   * Test that copying over an existing file fails when FILE_EXISTS_ERROR is
1867
   * specified.
1868
   */
1869
  function testExistingError() {
1870
    $contents = $this->randomName(10);
1871
    $source = $this->createFile();
1872
    $target = $this->createFile(NULL, $contents);
1873
    $this->assertDifferentFile($source, $target);
1874

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

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

    
1883
    // Check that the correct hooks were called.
1884
    $this->assertFileHooksCalled(array());
1885

    
1886
    $this->assertFileUnchanged($source, file_load($source->fid, TRUE));
1887
    $this->assertFileUnchanged($target, file_load($target->fid, TRUE));
1888
  }
1889
}
1890

    
1891

    
1892
/**
1893
 * Tests the file_load() function.
1894
 */
1895
class FileLoadTest extends FileHookTestCase {
1896
  public static function getInfo() {
1897
    return array(
1898
      'name' => 'File loading',
1899
      'description' => 'Tests the file_load() function.',
1900
      'group' => 'File API',
1901
    );
1902
  }
1903

    
1904
  /**
1905
   * Try to load a non-existent file by fid.
1906
   */
1907
  function testLoadMissingFid() {
1908
    $this->assertFalse(file_load(-1), "Try to load an invalid fid fails.");
1909
    $this->assertFileHooksCalled(array());
1910
  }
1911

    
1912
  /**
1913
   * Try to load a non-existent file by URI.
1914
   */
1915
  function testLoadMissingFilepath() {
1916
    $files = file_load_multiple(array(), array('uri' => 'foobar://misc/druplicon.png'));
1917
    $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
1918
    $this->assertFileHooksCalled(array());
1919
  }
1920

    
1921
  /**
1922
   * Try to load a non-existent file by status.
1923
   */
1924
  function testLoadInvalidStatus() {
1925
    $files = file_load_multiple(array(), array('status' => -99));
1926
    $this->assertFalse(reset($files), "Trying to load a file with an invalid status fails.");
1927
    $this->assertFileHooksCalled(array());
1928
  }
1929

    
1930
  /**
1931
   * Load a single file and ensure that the correct values are returned.
1932
   */
1933
  function testSingleValues() {
1934
    // Create a new file object from scratch so we know the values.
1935
    $file = $this->createFile('druplicon.txt', NULL, 'public');
1936

    
1937
    $by_fid_file = file_load($file->fid);
1938
    $this->assertFileHookCalled('load');
1939
    $this->assertTrue(is_object($by_fid_file), 'file_load() returned an object.');
1940
    $this->assertEqual($by_fid_file->fid, $file->fid, 'Loading by fid got the same fid.', 'File');
1941
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
1942
    $this->assertEqual($by_fid_file->filename, $file->filename, 'Loading by fid got the correct filename.', 'File');
1943
    $this->assertEqual($by_fid_file->filemime, $file->filemime, 'Loading by fid got the correct MIME type.', 'File');
1944
    $this->assertEqual($by_fid_file->status, $file->status, 'Loading by fid got the correct status.', 'File');
1945
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
1946
  }
1947

    
1948
  /**
1949
   * This will test loading file data from the database.
1950
   */
1951
  function testMultiple() {
1952
    // Create a new file object.
1953
    $file = $this->createFile('druplicon.txt', NULL, 'public');
1954

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

    
1964
    // Load by fid.
1965
    file_test_reset();
1966
    $by_fid_files = file_load_multiple(array($file->fid), array());
1967
    $this->assertFileHookCalled('load');
1968
    $this->assertEqual(1, count($by_fid_files), 'file_load_multiple() returned an array of the correct size.');
1969
    $by_fid_file = reset($by_fid_files);
1970
    $this->assertTrue($by_fid_file->file_test['loaded'], 'file_test_file_load() was able to modify the file during load.');
1971
    $this->assertEqual($by_fid_file->uri, $file->uri, 'Loading by fid got the correct filepath.', 'File');
1972
  }
1973
}
1974

    
1975
/**
1976
 * Tests the file_save() function.
1977
 */
1978
class FileSaveTest extends FileHookTestCase {
1979
  public static function getInfo() {
1980
    return array(
1981
      'name' => 'File saving',
1982
      'description' => 'Tests the file_save() function.',
1983
      'group' => 'File API',
1984
    );
1985
  }
1986

    
1987
  function testFileSave() {
1988
    // Create a new file object.
1989
    $file = array(
1990
      'uid' => 1,
1991
      'filename' => 'druplicon.txt',
1992
      'uri' => 'public://druplicon.txt',
1993
      'filemime' => 'text/plain',
1994
      'timestamp' => 1,
1995
      'status' => FILE_STATUS_PERMANENT,
1996
    );
1997
    $file = (object) $file;
1998
    file_put_contents($file->uri, 'hello world');
1999

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

    
2003
    // Check that the correct hooks were called.
2004
    $this->assertFileHooksCalled(array('insert'));
2005

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

    
2014

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

    
2020
    // Check that the correct hooks were called.
2021
    $this->assertFileHooksCalled(array('load', 'update'));
2022

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

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

    
2044
/**
2045
 * Tests file usage functions.
2046
 */
2047
class FileUsageTest extends FileTestCase {
2048
  public static function getInfo() {
2049
    return array(
2050
      'name' => 'File usage',
2051
      'description' => 'Tests the file usage functions.',
2052
      'group' => 'File',
2053
    );
2054
  }
2055

    
2056
  /**
2057
   * Tests file_usage_list().
2058
   */
2059
  function testGetUsage() {
2060
    $file = $this->createFile();
2061
    db_insert('file_usage')
2062
      ->fields(array(
2063
        'fid' => $file->fid,
2064
        'module' => 'testing',
2065
        'type' => 'foo',
2066
        'id' => 1,
2067
        'count' => 1
2068
      ))
2069
      ->execute();
2070
    db_insert('file_usage')
2071
      ->fields(array(
2072
        'fid' => $file->fid,
2073
        'module' => 'testing',
2074
        'type' => 'bar',
2075
        'id' => 2,
2076
        'count' => 2
2077
      ))
2078
      ->execute();
2079

    
2080
    $usage = file_usage_list($file);
2081

    
2082
    $this->assertEqual(count($usage['testing']), 2, 'Returned the correct number of items.');
2083
    $this->assertTrue(isset($usage['testing']['foo'][1]), 'Returned the correct id.');
2084
    $this->assertTrue(isset($usage['testing']['bar'][2]), 'Returned the correct id.');
2085
    $this->assertEqual($usage['testing']['foo'][1], 1, 'Returned the correct count.');
2086
    $this->assertEqual($usage['testing']['bar'][2], 2, 'Returned the correct count.');
2087
  }
2088

    
2089
  /**
2090
   * Tests file_usage_add().
2091
   */
2092
  function testAddUsage() {
2093
    $file = $this->createFile();
2094
    file_usage_add($file, 'testing', 'foo', 1);
2095
    // Add the file twice to ensure that the count is incremented rather than
2096
    // creating additional records.
2097
    file_usage_add($file, 'testing', 'bar', 2);
2098
    file_usage_add($file, 'testing', 'bar', 2);
2099

    
2100
    $usage = db_select('file_usage', 'f')
2101
      ->fields('f')
2102
      ->condition('f.fid', $file->fid)
2103
      ->execute()
2104
      ->fetchAllAssoc('id');
2105
    $this->assertEqual(count($usage), 2, 'Created two records');
2106
    $this->assertEqual($usage[1]->module, 'testing', 'Correct module');
2107
    $this->assertEqual($usage[2]->module, 'testing', 'Correct module');
2108
    $this->assertEqual($usage[1]->type, 'foo', 'Correct type');
2109
    $this->assertEqual($usage[2]->type, 'bar', 'Correct type');
2110
    $this->assertEqual($usage[1]->count, 1, 'Correct count');
2111
    $this->assertEqual($usage[2]->count, 2, 'Correct count');
2112
  }
2113

    
2114
  /**
2115
   * Tests file_usage_delete().
2116
   */
2117
  function testRemoveUsage() {
2118
    $file = $this->createFile();
2119
    db_insert('file_usage')
2120
      ->fields(array(
2121
        'fid' => $file->fid,
2122
        'module' => 'testing',
2123
        'type' => 'bar',
2124
        'id' => 2,
2125
        'count' => 3,
2126
      ))
2127
      ->execute();
2128

    
2129
    // Normal decrement.
2130
    file_usage_delete($file, 'testing', 'bar', 2);
2131
    $count = db_select('file_usage', 'f')
2132
      ->fields('f', array('count'))
2133
      ->condition('f.fid', $file->fid)
2134
      ->execute()
2135
      ->fetchField();
2136
    $this->assertEqual(2, $count, 'The count was decremented correctly.');
2137

    
2138
    // Multiple decrement and removal.
2139
    file_usage_delete($file, 'testing', 'bar', 2, 2);
2140
    $count = db_select('file_usage', 'f')
2141
      ->fields('f', array('count'))
2142
      ->condition('f.fid', $file->fid)
2143
      ->execute()
2144
      ->fetchField();
2145
    $this->assertIdentical(FALSE, $count, 'The count was removed entirely when empty.');
2146

    
2147
    // Non-existent decrement.
2148
    file_usage_delete($file, 'testing', 'bar', 2);
2149
    $count = db_select('file_usage', 'f')
2150
      ->fields('f', array('count'))
2151
      ->condition('f.fid', $file->fid)
2152
      ->execute()
2153
      ->fetchField();
2154
    $this->assertIdentical(FALSE, $count, 'Decrementing non-exist record complete.');
2155
  }
2156
}
2157

    
2158
/**
2159
 * Tests the file_validate() function..
2160
 */
2161
class FileValidateTest extends FileHookTestCase {
2162
  public static function getInfo() {
2163
    return array(
2164
      'name' => 'File validate',
2165
      'description' => 'Tests the file_validate() function.',
2166
      'group' => 'File API',
2167
    );
2168
  }
2169

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

    
2176
    // Empty validators.
2177
    $this->assertEqual(file_validate($file, array()), array(), 'Validating an empty array works successfully.');
2178
    $this->assertFileHooksCalled(array('validate'));
2179

    
2180
    // Use the file_test.module's test validator to ensure that passing tests
2181
    // return correctly.
2182
    file_test_reset();
2183
    file_test_set_return('validate', array());
2184
    $passing = array('file_test_validator' => array(array()));
2185
    $this->assertEqual(file_validate($file, $passing), array(), 'Validating passes.');
2186
    $this->assertFileHooksCalled(array('validate'));
2187

    
2188
    // Now test for failures in validators passed in and by hook_validate.
2189
    file_test_reset();
2190
    file_test_set_return('validate', array('Epic fail'));
2191
    $failing = array('file_test_validator' => array(array('Failed', 'Badly')));
2192
    $this->assertEqual(file_validate($file, $failing), array('Failed', 'Badly', 'Epic fail'), 'Validating returns errors.');
2193
    $this->assertFileHooksCalled(array('validate'));
2194
  }
2195
}
2196

    
2197
/**
2198
 *  Tests the file_save_data() function.
2199
 */
2200
class FileSaveDataTest extends FileHookTestCase {
2201
  public static function getInfo() {
2202
    return array(
2203
      'name' => 'File save data',
2204
      'description' => 'Tests the file save data function.',
2205
      'group' => 'File API',
2206
    );
2207
  }
2208

    
2209
  /**
2210
   * Test the file_save_data() function when no filename is provided.
2211
   */
2212
  function testWithoutFilename() {
2213
    $contents = $this->randomName(8);
2214

    
2215
    $result = file_save_data($contents);
2216
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2217

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

    
2224
    // Check that the correct hooks were called.
2225
    $this->assertFileHooksCalled(array('insert'));
2226

    
2227
    // Verify that what was returned is what's in the database.
2228
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2229
  }
2230

    
2231
  /**
2232
   * Test the file_save_data() function when a filename is provided.
2233
   */
2234
  function testWithFilename() {
2235
    $contents = $this->randomName(8);
2236

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

    
2240
    $result = file_save_data($contents, 'public://' . $filename);
2241
    $this->assertTrue($result, 'Unnamed file saved correctly.');
2242

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

    
2249
    // Check that the correct hooks were called.
2250
    $this->assertFileHooksCalled(array('insert'));
2251

    
2252
    // Verify that what was returned is what's in the database.
2253
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2254
  }
2255

    
2256
  /**
2257
   * Test file_save_data() when renaming around an existing file.
2258
   */
2259
  function testExistingRename() {
2260
    // Setup a file to overwrite.
2261
    $existing = $this->createFile();
2262
    $contents = $this->randomName(8);
2263

    
2264
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_RENAME);
2265
    $this->assertTrue($result, 'File saved successfully.');
2266

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

    
2273
    // Check that the correct hooks were called.
2274
    $this->assertFileHooksCalled(array('insert'));
2275

    
2276
    // Ensure that the existing file wasn't overwritten.
2277
    $this->assertDifferentFile($existing, $result);
2278
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2279

    
2280
    // Verify that was returned is what's in the database.
2281
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2282
  }
2283

    
2284
  /**
2285
   * Test file_save_data() when replacing an existing file.
2286
   */
2287
  function testExistingReplace() {
2288
    // Setup a file to overwrite.
2289
    $existing = $this->createFile();
2290
    $contents = $this->randomName(8);
2291

    
2292
    $result = file_save_data($contents, $existing->uri, FILE_EXISTS_REPLACE);
2293
    $this->assertTrue($result, 'File saved successfully.');
2294

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

    
2301
    // Check that the correct hooks were called.
2302
    $this->assertFileHooksCalled(array('load', 'update'));
2303

    
2304
    // Verify that the existing file was re-used.
2305
    $this->assertSameFile($existing, $result);
2306

    
2307
    // Verify that what was returned is what's in the database.
2308
    $this->assertFileUnchanged($result, file_load($result->fid, TRUE));
2309
  }
2310

    
2311
  /**
2312
   * Test that file_save_data() fails overwriting an existing file.
2313
   */
2314
  function testExistingError() {
2315
    $contents = $this->randomName(8);
2316
    $existing = $this->createFile(NULL, $contents);
2317

    
2318
    // Check the overwrite error.
2319
    $result = file_save_data('asdf', $existing->uri, FILE_EXISTS_ERROR);
2320
    $this->assertFalse($result, 'Overwriting a file fails when FILE_EXISTS_ERROR is specified.');
2321
    $this->assertEqual($contents, file_get_contents($existing->uri), 'Contents of existing file were unchanged.');
2322

    
2323
    // Check that no hooks were called while failing.
2324
    $this->assertFileHooksCalled(array());
2325

    
2326
    // Ensure that the existing file wasn't overwritten.
2327
    $this->assertFileUnchanged($existing, file_load($existing->fid, TRUE));
2328
  }
2329
}
2330

    
2331
/**
2332
 * Tests for download/file transfer functions.
2333
 */
2334
class FileDownloadTest extends FileTestCase {
2335
  public static function getInfo() {
2336
    return array(
2337
      'name' => 'File download',
2338
      'description' => 'Tests for file download/transfer functions.',
2339
      'group' => 'File API',
2340
    );
2341
  }
2342

    
2343
  function setUp() {
2344
    parent::setUp('file_test');
2345
    // Clear out any hook calls.
2346
    file_test_reset();
2347
  }
2348

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

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

    
2372
  /**
2373
   * Test the private file transfer system.
2374
   */
2375
  function testPrivateFileTransfer() {
2376
    // Set file downloads to private so handler functions get called.
2377

    
2378
    // Create a file.
2379
    $contents = $this->randomName(8);
2380
    $file = $this->createFile(NULL, $contents, 'private');
2381
    $url  = file_create_url($file->uri);
2382

    
2383
    // Set file_test access header to allow the download.
2384
    file_test_set_return('download', array('x-foo' => 'Bar'));
2385
    $this->drupalGet($url);
2386
    $headers = $this->drupalGetHeaders();
2387
    $this->assertEqual($headers['x-foo'], 'Bar', 'Found header set by file_test module on private download.');
2388
    $this->assertResponse(200, 'Correctly allowed access to a file when file_test provides headers.');
2389

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

    
2393
    // Deny access to all downloads via a -1 header.
2394
    file_test_set_return('download', -1);
2395
    $this->drupalHead($url);
2396
    $this->assertResponse(403, 'Correctly denied access to a file when file_test sets the header to -1.');
2397

    
2398
    // Try non-existent file.
2399
    $url = file_create_url('private://' . $this->randomName());
2400
    $this->drupalHead($url);
2401
    $this->assertResponse(404, 'Correctly returned 404 response for a non-existent file.');
2402
  }
2403

    
2404
  /**
2405
   * Test file_create_url().
2406
   */
2407
  function testFileCreateUrl() {
2408
    global $base_url;
2409

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

    
2420
    $this->checkUrl('public', '', $basename, $base_url . '/' . file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath() . '/' . $basename_encoded);
2421
    $this->checkUrl('private', '', $basename, $base_url . '/system/files/' . $basename_encoded);
2422
    $this->checkUrl('private', '', $basename, $base_url . '/?q=system/files/' . $basename_encoded, '0');
2423
  }
2424

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

    
2446
    // Convert $filename to a valid filename, i.e. strip characters not
2447
    // supported by the filesystem, and create the file in the specified
2448
    // directory.
2449
    $filepath = file_create_filename($filename, $directory);
2450
    $directory_uri = $scheme . '://' . dirname($filepath);
2451
    file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
2452
    $file = $this->createFile($filepath, NULL, $scheme);
2453

    
2454
    $url = file_create_url($file->uri);
2455
    $this->assertEqual($url, $expected_url, 'Generated URL matches expected URL.');
2456

    
2457
    if ($scheme == 'private') {
2458
      // Tell the implementation of hook_file_download() in file_test.module
2459
      // that this file may be downloaded.
2460
      file_test_set_return('download', array('x-foo' => 'Bar'));
2461
    }
2462

    
2463
    $this->drupalGet($url);
2464
    if ($this->assertResponse(200) == 'pass') {
2465
      $this->assertRaw(file_get_contents($file->uri), 'Contents of the file are correct.');
2466
    }
2467

    
2468
    file_delete($file);
2469
  }
2470
}
2471

    
2472
/**
2473
 * Tests for file URL rewriting.
2474
 */
2475
class FileURLRewritingTest extends FileTestCase {
2476
  public static function getInfo() {
2477
    return array(
2478
      'name' => 'File URL rewriting',
2479
      'description' => 'Tests for file URL rewriting.',
2480
      'group' => 'File',
2481
    );
2482
  }
2483

    
2484
  function setUp() {
2485
    parent::setUp('file_test');
2486
  }
2487

    
2488
  /**
2489
   * Test the generating of rewritten shipped file URLs.
2490
   */
2491
  function testShippedFileURL()  {
2492
    // Test generating an URL to a shipped file (i.e. a file that is part of
2493
    // Drupal core, a module or a theme, for example a JavaScript file).
2494

    
2495
    // Test alteration of file URLs to use a CDN.
2496
    variable_set('file_test_hook_file_url_alter', 'cdn');
2497
    $filepath = 'misc/jquery.js';
2498
    $url = file_create_url($filepath);
2499
    $this->assertEqual(FILE_URL_TEST_CDN_1 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2500
    $filepath = 'misc/favicon.ico';
2501
    $url = file_create_url($filepath);
2502
    $this->assertEqual(FILE_URL_TEST_CDN_2 . '/' . $filepath, $url, 'Correctly generated a CDN URL for a shipped file.');
2503

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

    
2513
    // Test alteration of file URLs to use protocol-relative URLs.
2514
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2515
    $filepath = 'misc/jquery.js';
2516
    $url = file_create_url($filepath);
2517
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2518
    $filepath = 'misc/favicon.ico';
2519
    $url = file_create_url($filepath);
2520
    $this->assertEqual('/' . base_path() . '/' . $filepath, $url, 'Correctly generated a protocol-relative URL for a shipped file.');
2521
  }
2522

    
2523
  /**
2524
   * Test the generating of rewritten public created file URLs.
2525
   */
2526
  function testPublicCreatedFileURL() {
2527
    // Test generating an URL to a created file.
2528

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

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

    
2542
    // Test alteration of file URLs to use a protocol-relative URLs.
2543
    variable_set('file_test_hook_file_url_alter', 'protocol-relative');
2544
    $file = $this->createFile();
2545
    $url = file_create_url($file->uri);
2546
    $this->assertEqual('/' . base_path() . '/' . $public_directory_path . '/' . $file->filename, $url, 'Correctly generated a protocol-relative URL for a created file.');
2547
  }
2548
}
2549

    
2550
/**
2551
 * Tests for file_munge_filename() and file_unmunge_filename().
2552
 */
2553
class FileNameMungingTest extends FileTestCase {
2554
  public static function getInfo() {
2555
    return array(
2556
      'name' => 'File naming',
2557
      'description' => 'Test filename munging and unmunging.',
2558
      'group' => 'File API',
2559
    );
2560
  }
2561

    
2562
  function setUp() {
2563
    parent::setUp();
2564
    $this->bad_extension = 'php';
2565
    $this->name = $this->randomName() . '.' . $this->bad_extension . '.txt';
2566
    $this->name_with_uc_ext = $this->randomName() . '.' . strtoupper($this->bad_extension) . '.txt';
2567
  }
2568

    
2569
  /**
2570
   * Create a file and munge/unmunge the name.
2571
   */
2572
  function testMunging() {
2573
    // Disable insecure uploads.
2574
    variable_set('allow_insecure_uploads', 0);
2575
    $munged_name = file_munge_filename($this->name, '', TRUE);
2576
    $messages = drupal_get_messages();
2577
    $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.');
2578
    $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)));
2579
  }
2580

    
2581
  /**
2582
   * Tests munging with a null byte in the filename.
2583
   */
2584
  function testMungeNullByte() {
2585
    $prefix = $this->randomName();
2586
    $filename = $prefix . '.' . $this->bad_extension . "\0.txt";
2587
    $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.');
2588
  }
2589

    
2590
  /**
2591
   * If the allow_insecure_uploads variable evaluates to true, the file should
2592
   * come out untouched, no matter how evil the filename.
2593
   */
2594
  function testMungeIgnoreInsecure() {
2595
    variable_set('allow_insecure_uploads', 1);
2596
    $munged_name = file_munge_filename($this->name, '');
2597
    $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)));
2598
  }
2599

    
2600
  /**
2601
   * White listed extensions are ignored by file_munge_filename().
2602
   */
2603
  function testMungeIgnoreWhitelisted() {
2604
    // Declare our extension as whitelisted. The declared extensions should
2605
    // be case insensitive so test using one with a different case.
2606
    $munged_name = file_munge_filename($this->name_with_uc_ext, $this->bad_extension);
2607
    $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)));
2608
    // The allowed extensions should also be normalized.
2609
    $munged_name = file_munge_filename($this->name, strtoupper($this->bad_extension));
2610
    $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)));
2611
  }
2612

    
2613
  /**
2614
   * Ensure that unmunge gets your name back.
2615
   */
2616
  function testUnMunge() {
2617
    $munged_name = file_munge_filename($this->name, '', FALSE);
2618
    $unmunged_name = file_unmunge_filename($munged_name);
2619
    $this->assertIdentical($unmunged_name, $this->name, format_string('The unmunged (%unmunged) filename matches the original (%original)', array('%unmunged' => $unmunged_name, '%original' => $this->name)));
2620
  }
2621
}
2622

    
2623
/**
2624
 * Tests for file_get_mimetype().
2625
 */
2626
class FileMimeTypeTest extends DrupalWebTestCase {
2627
  function setUp() {
2628
    parent::setUp('file_test');
2629
  }
2630

    
2631
  public static function getInfo() {
2632
    return array(
2633
      'name' => 'File mimetypes',
2634
      'description' => 'Test filename mimetype detection.',
2635
      'group' => 'File API',
2636
    );
2637
  }
2638

    
2639
  /**
2640
   * Test mapping of mimetypes from filenames.
2641
   */
2642
  public function testFileMimeTypeDetection() {
2643
    $prefix = 'public://';
2644

    
2645
    $test_case = array(
2646
      'test.jar' => 'application/java-archive',
2647
      'test.jpeg' => 'image/jpeg',
2648
      'test.JPEG' => 'image/jpeg',
2649
      'test.jpg' => 'image/jpeg',
2650
      'test.jar.jpg' => 'image/jpeg',
2651
      'test.jpg.jar' => 'application/java-archive',
2652
      'test.pcf.Z' => 'application/x-font',
2653
      'pcf.z' => 'application/octet-stream',
2654
      'jar' => 'application/octet-stream',
2655
      'some.junk' => 'application/octet-stream',
2656
      'foo.file_test_1' => 'madeup/file_test_1',
2657
      'foo.file_test_2' => 'madeup/file_test_2',
2658
      'foo.doc' => 'madeup/doc',
2659
      'test.ogg' => 'audio/ogg',
2660
    );
2661

    
2662
    // Test using default mappings.
2663
    foreach ($test_case as $input => $expected) {
2664
      // Test stream [URI].
2665
      $output = file_get_mimetype($prefix . $input);
2666
      $this->assertIdentical($output, $expected, format_string('Mimetype for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2667

    
2668
      // Test normal path equivalent
2669
      $output = file_get_mimetype($input);
2670
      $this->assertIdentical($output, $expected, format_string('Mimetype (using default mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2671
    }
2672

    
2673
    // Now test passing in the map.
2674
    $mapping = array(
2675
      'mimetypes' => array(
2676
        0 => 'application/java-archive',
2677
        1 => 'image/jpeg',
2678
      ),
2679
      'extensions' => array(
2680
         'jar' => 0,
2681
         'jpg' => 1,
2682
      )
2683
    );
2684

    
2685
    $test_case = array(
2686
      'test.jar' => 'application/java-archive',
2687
      'test.jpeg' => 'application/octet-stream',
2688
      'test.jpg' => 'image/jpeg',
2689
      'test.jar.jpg' => 'image/jpeg',
2690
      'test.jpg.jar' => 'application/java-archive',
2691
      'test.pcf.z' => 'application/octet-stream',
2692
      'pcf.z' => 'application/octet-stream',
2693
      'jar' => 'application/octet-stream',
2694
      'some.junk' => 'application/octet-stream',
2695
      'foo.file_test_1' => 'application/octet-stream',
2696
      'foo.file_test_2' => 'application/octet-stream',
2697
      'foo.doc' => 'application/octet-stream',
2698
      'test.ogg' => 'application/octet-stream',
2699
    );
2700

    
2701
    foreach ($test_case as $input => $expected) {
2702
      $output = file_get_mimetype($input, $mapping);
2703
      $this->assertIdentical($output, $expected, format_string('Mimetype (using passed-in mappings) for %input is %output (expected: %expected).', array('%input' => $input, '%output' => $output, '%expected' => $expected)));
2704
    }
2705
  }
2706
}
2707

    
2708
/**
2709
 * Tests stream wrapper functions.
2710
 */
2711
class StreamWrapperTest extends DrupalWebTestCase {
2712

    
2713
  protected $scheme = 'dummy';
2714
  protected $classname = 'DrupalDummyStreamWrapper';
2715

    
2716
  public static function getInfo() {
2717
    return array(
2718
      'name' => 'Stream wrappers',
2719
      'description' => 'Tests stream wrapper functions.',
2720
      'group' => 'File API',
2721
    );
2722
  }
2723

    
2724
  function setUp() {
2725
    parent::setUp('file_test');
2726
    drupal_static_reset('file_get_stream_wrappers');
2727
  }
2728

    
2729
  function tearDown() {
2730
    parent::tearDown();
2731
    stream_wrapper_unregister($this->scheme);
2732
  }
2733

    
2734
  /**
2735
   * Test the getClassName() function.
2736
   */
2737
  function testGetClassName() {
2738
    // Check the dummy scheme.
2739
    $this->assertEqual($this->classname, file_stream_wrapper_get_class($this->scheme), 'Got correct class name for dummy scheme.');
2740
    // Check core's scheme.
2741
    $this->assertEqual('DrupalPublicStreamWrapper', file_stream_wrapper_get_class('public'), 'Got correct class name for public scheme.');
2742
  }
2743

    
2744
  /**
2745
   * Test the file_stream_wrapper_get_instance_by_scheme() function.
2746
   */
2747
  function testGetInstanceByScheme() {
2748
    $instance = file_stream_wrapper_get_instance_by_scheme($this->scheme);
2749
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy scheme.');
2750

    
2751
    $instance = file_stream_wrapper_get_instance_by_scheme('public');
2752
    $this->assertEqual('DrupalPublicStreamWrapper', get_class($instance), 'Got correct class type for public scheme.');
2753
  }
2754

    
2755
  /**
2756
   * Test the URI and target functions.
2757
   */
2758
  function testUriFunctions() {
2759
    $instance = file_stream_wrapper_get_instance_by_uri($this->scheme . '://foo');
2760
    $this->assertEqual($this->classname, get_class($instance), 'Got correct class type for dummy URI.');
2761

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

    
2765
    // Test file_uri_target().
2766
    $this->assertEqual(file_uri_target('public://foo/bar.txt'), 'foo/bar.txt', 'Got a valid stream target from public://foo/bar.txt.');
2767
    $this->assertFalse(file_uri_target('foo/bar.txt'), 'foo/bar.txt is not a valid stream.');
2768

    
2769
    // Test file_build_uri() and DrupalLocalStreamWrapper::getDirectoryPath().
2770
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'public://foo/bar.txt', 'Expected scheme was added.');
2771
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('public')->getDirectoryPath(), variable_get('file_public_path'), 'Expected default directory path was returned.');
2772
    $this->assertEqual(file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath(), variable_get('file_temporary_path'), 'Expected temporary directory path was returned.');
2773

    
2774
    variable_set('file_default_scheme', 'private');
2775
    $this->assertEqual(file_build_uri('foo/bar.txt'), 'private://foo/bar.txt', 'Got a valid URI from foo/bar.txt.');
2776
  }
2777

    
2778
  /**
2779
   * Test the scheme functions.
2780
   */
2781
  function testGetValidStreamScheme() {
2782
    $this->assertEqual('foo', file_uri_scheme('foo://pork//chops'), 'Got the correct scheme from foo://asdf');
2783
    $this->assertTrue(file_stream_wrapper_valid_scheme(file_uri_scheme('public://asdf')), 'Got a valid stream scheme from public://asdf');
2784
    $this->assertFalse(file_stream_wrapper_valid_scheme(file_uri_scheme('foo://asdf')), 'Did not get a valid stream scheme from foo://asdf');
2785
  }
2786

    
2787
  /**
2788
   * Tests that phar stream wrapper is registered as expected.
2789
   *
2790
   * @see file_get_stream_wrappers()
2791
   */
2792
  public function testPharStreamWrapperRegistration() {
2793
    if (!class_exists('Phar', FALSE)) {
2794
      $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'PHP is compiled without phar support. Therefore, no phar stream wrapper is registered.');
2795
    }
2796
    elseif (version_compare(PHP_VERSION, '5.3.3', '<')) {
2797
      $this->assertFalse(in_array('phar', stream_get_wrappers(), TRUE), 'The PHP version is <5.3.3. The built-in phar stream wrapper has been unregistered and not replaced.');
2798
    }
2799
    else {
2800
      $this->assertTrue(in_array('phar', stream_get_wrappers(), TRUE), 'A phar stream wrapper is registered.');
2801
      $this->assertFalse(file_stream_wrapper_valid_scheme('phar'), 'The phar scheme is not a valid scheme for Drupal File API usage.');
2802
    }
2803

    
2804
    // Ensure that calling file_get_stream_wrappers() multiple times, both
2805
    // without and with a drupal_static_reset() in between, does not create
2806
    // errors due to the PharStreamWrapperManager singleton.
2807
    file_get_stream_wrappers();
2808
    file_get_stream_wrappers();
2809
    drupal_static_reset('file_get_stream_wrappers');
2810
    file_get_stream_wrappers();
2811
  }
2812

    
2813
  /**
2814
   * Tests that only valid phar files can be used.
2815
   */
2816
  public function testPharFile() {
2817
    if (!in_array('phar', stream_get_wrappers(), TRUE)) {
2818
      $this->pass('There is no phar stream wrapper registered.');
2819
      // Nothing else in this test is relevant when there's no phar stream
2820
      // wrapper. testPharStreamWrapperRegistration() is sufficient for testing
2821
      // the conditions of when the stream wrapper should or should not be
2822
      // registered.
2823
      return;
2824
    }
2825

    
2826
    $base = dirname(dirname(__FILE__)) . '/files';
2827

    
2828
    // Ensure that file operations via the phar:// stream wrapper work for phar
2829
    // files with the .phar extension.
2830
    $this->assertFalse(file_exists("phar://$base/phar-1.phar/no-such-file.php"));
2831
    $this->assertTrue(file_exists("phar://$base/phar-1.phar/index.php"));
2832
    $file_contents = file_get_contents("phar://$base/phar-1.phar/index.php");
2833
    $expected_hash = 'c7e7904ea573c5ebea3ef00bb08c1f86af1a45961fbfbeb1892ff4a98fd73ad5';
2834
    $this->assertIdentical($expected_hash, hash('sha256', $file_contents));
2835

    
2836
    // Ensure that file operations via the phar:// stream wrapper throw an
2837
    // exception for files without the .phar extension.
2838
    try {
2839
      file_exists("phar://$base/image-2.jpg/index.php");
2840
      $this->fail('Expected exception failed to be thrown when accessing an invalid phar file.');
2841
    }
2842
    catch (Exception $e) {
2843
      $this->assertEqual(get_class($e), 'TYPO3\PharStreamWrapper\Exception', 'Expected exception thrown when accessing an invalid phar file.');
2844
    }
2845
  }
2846
}