Project

General

Profile

Revision 1f142f4f

Added by Florent Torregrosa over 8 years ago

Issue #592: Update file_entity to version 7.x-2.0-beta2.

View differences:

drupal7/sites/all/modules/file_entity/file_entity.test
6 6
 */
7 7

  
8 8
class FileEntityTestHelper extends DrupalWebTestCase {
9
  protected $files = array();
10

  
11 9
  function setUp() {
12 10
    $modules = func_get_args();
13 11
    if (isset($modules[0]) && is_array($modules[0])) {
......
17 15
    parent::setUp($modules);
18 16
  }
19 17

  
20
  protected function setUpFiles($defaults = array()) {
21
    // Populate defaults array.
22
    $defaults += array(
23
      'uid' => 1,
24
      'status' => FILE_STATUS_PERMANENT,
25
    );
26

  
27
    $types = array('text', 'image');
28
    foreach ($types as $type) {
29
      foreach ($this->drupalGetTestFiles($type) as $file) {
30
        foreach ($defaults as $key => $value) {
31
          $file->$key = $value;
32
        }
33
        $this->files[$type][] = file_save($file);
34
      }
35
    }
36
  }
37

  
38
  protected function createFileType($overrides = array()) {
39
    $type = new stdClass();
40
    $type->type = 'test';
41
    $type->label = "Test";
42
    $type->description = '';
43
    $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
44

  
45
    foreach ($overrides as $k => $v) {
46
      $type->$k = $v;
47
    }
48

  
49
    file_type_save($type);
50
    return $type;
51
  }
52

  
53
  /**
54
   * Helper for testFileEntityPrivateDownloadAccess() test.
55
   *
56
   * Defines several cases for accesing private files.
57
   *
58
   * @return array
59
   *   Array of associative arrays, each one having the next keys:
60
   *   - "message" string with the assertion message.
61
   *   - "permissions" array of permissions or NULL for anonymous user.
62
   *   - "expect" expected HTTP response code.
63
   *   - "owner" Optional boolean indicating if the user is a file owner.
64
   */
65
  protected function getPrivateDownloadAccessCases() {
66
    return array(
67
      array(
68
        'message' => "File owners cannot download their own files unless they are granted the 'view own private files' permission.",
69
        'permissions' => array(),
70
        'expect' => 403,
71
        'owner' => TRUE,
72
      ),
73
      array(
74
        'message' => "File owners can download their own files as they have been granted the 'view own private files' permission.",
75
        'permissions' => array('view own private files'),
76
        'expect' => 200,
77
        'owner' => TRUE,
78
      ),
79
      array(
80
        'message' => "Anonymous users cannot download private files.",
81
        'permissions' => NULL,
82
        'expect' => 403,
83
      ),
84
      array(
85
        'message' => "Authenticated users cannot download each other's private files.",
86
        'permissions' => array(),
87
        'expect' => 403,
88
      ),
89
      array(
90
        'message' => "Users who can view public files are not able to download private files.",
91
        'permissions' => array('view files'),
92
        'expect' => 403,
93
      ),
94
      array(
95
        'message' => "Users who bypass file access can download any file.",
96
        'permissions' => array('bypass file access'),
97
        'expect' => 200,
98
      ),
99
    );
100
  }
101

  
102 18
  /**
103 19
   * Retrieves a sample file of the specified type.
104 20
   */
......
112 28
    return $file;
113 29
  }
114 30

  
31
  /**
32
   * Retrieves the fid of the last inserted file.
33
   */
34
  function getLastFileId() {
35
    return (int) db_query('SELECT MAX(fid) FROM {file_managed}')->fetchField();
36
  }
37

  
115 38
  /**
116 39
   * Get a file from the database based on its filename.
117 40
   *
......
131 54
  }
132 55

  
133 56
  protected function createFileEntity($settings = array()) {
134
    $file = new stdClass();
135

  
136 57
    // Populate defaults array.
137 58
    $settings += array(
138 59
      'filepath' => 'Файл для тестирования ' . $this->randomName(), // Prefix with non-latin characters to ensure that all file-related tests work with international filenames.
......
181 102
    return $file;
182 103
  }
183 104

  
105
  protected function createFileType($overrides = array()) {
106
    $type = new stdClass();
107
    $type->type = 'test';
108
    $type->label = "Test";
109
    $type->description = '';
110
    $type->mimetypes = array('image/jpeg', 'image/gif', 'image/png', 'image/tiff');
111

  
112
    foreach ($overrides as $k => $v) {
113
      $type->$k = $v;
114
    }
115

  
116
    file_type_save($type);
117
    return $type;
118
  }
119

  
184 120
  /**
185 121
   * Overrides DrupalWebTestCase::drupalGetToken() to support the hash salt.
186 122
   *
......
192 128
  }
193 129
}
194 130

  
131
/**
132
 * Tests file type classification functionality.
133
 */
195 134
class FileEntityFileTypeClassificationTestCase extends DrupalWebTestCase {
196 135
  public static function getInfo() {
197 136
    return array(
......
205 144
    parent::setUp();
206 145
  }
207 146

  
208
  /**
209
   * Get the file type of a given file.
210
   *
211
   * @param $file
212
   *   A file object.
213
   *
214
   * @return
215
   *   The file's file type as a string.
216
   */
217
  function getFileType($file) {
218
    $type = db_select('file_managed', 'fm')
219
      ->fields('fm', array('type'))
220
      ->condition('fid', $file->fid, '=')
221
      ->execute()
222
      ->fetchAssoc();
223

  
224
    return $type;
225
  }
226

  
227 147
  /**
228 148
   * Test that existing files are properly classified by file type.
229 149
   */
......
257 177
    $file_type = $this->getFileType($image_file);
258 178
    $this->assertEqual($file_type['type'], 'image', t('The image file was properly assigned the Image file type.'));
259 179
  }
180

  
181
  /**
182
   * Get the file type of a given file.
183
   *
184
   * @param $file
185
   *   A file object.
186
   *
187
   * @return
188
   *   The file's file type as a string.
189
   */
190
  function getFileType($file) {
191
    $type = db_select('file_managed', 'fm')
192
      ->fields('fm', array('type'))
193
      ->condition('fid', $file->fid, '=')
194
      ->execute()
195
      ->fetchAssoc();
196

  
197
    return $type;
198
  }
260 199
}
261 200

  
201
/**
202
 * Tests basic file entity functionality.
203
 */
262 204
class FileEntityUnitTestCase extends FileEntityTestHelper {
263 205
  public static function getInfo() {
264 206
    return array(
......
268 210
    );
269 211
  }
270 212

  
271
  function setUp() {
272
    parent::setUp();
273
    $this->setUpFiles();
274
  }
275

  
276 213
  /**
277 214
   * Regression tests for core issue http://drupal.org/node/1239376.
278 215
   */
......
289 226
    }
290 227
  }
291 228

  
229
  /**
230
   * Tests basic file entity properties.
231
   */
292 232
  function testFileEntity() {
293
    $file = reset($this->files['text']);
233
    // Save a raw file, turning it into a file entity.
234
    $file = $this->getTestFile('text');
235
    $file->uid = 1;
236
    $file->status = FILE_STATUS_PERMANENT;
237
    file_save($file);
294 238

  
295 239
    // Test entity ID, revision ID, and bundle.
296 240
    $ids = entity_extract_ids('file', $file);
......
301 245
    $this->assertEqual($uri['path'], "file/{$file->fid}");
302 246
  }
303 247

  
248
  /**
249
   * Tests storing image height and width as file metadata.
250
   */
304 251
  function testImageDimensions() {
305
    $files = array();
306
    $text_fids = array();
307 252
    // Test hook_file_insert().
308
    // Files have been saved as part of setup (in FileEntityTestHelper::setUpFiles).
309
    foreach ($this->files['image'] as $file) {
310
      $files[$file->fid] = $file->metadata;
311
      $this->assertTrue(isset($file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
312
      $this->assertTrue(isset($file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
313
    }
314
    foreach ($this->files['text'] as $file) {
315
      $text_fids[] = $file->fid;
316
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
317
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
318
    }
253
    $file = current($this->drupalGetTestFiles('image'));
254
    $image_file = file_save($file);
255
    $this->assertTrue(isset($image_file->metadata['height']), 'Image height retrieved on file_save() for an image file.');
256
    $this->assertTrue(isset($image_file->metadata['width']), 'Image width retrieved on file_save() for an image file.');
257

  
258
    $file = current($this->drupalGetTestFiles('text'));
259
    $text_file = file_save($file);
260
    $this->assertFalse(isset($text_file->metadata['height']), 'No image height retrieved on file_save() for an text file.');
261
    $this->assertFalse(isset($text_file->metadata['width']), 'No image width retrieved on file_save() for an text file.');
319 262

  
320 263
    // Test hook_file_load().
321 264
    // Clear the cache and load fresh files objects to test file_load behavior.
322 265
    entity_get_controller('file')->resetCache();
323
    foreach (file_load_multiple(array_keys($files)) as $file) {
324
      $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
325
      $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
326
      $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'], 'Loaded image height is equal to saved image height.');
327
      $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'], 'Loaded image width is equal to saved image width.');
328
    }
329
    foreach (file_load_multiple($text_fids) as $file) {
330
      $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
331
      $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
332
    }
266

  
267
    $file = file_load($image_file->fid);
268
    $this->assertTrue(isset($file->metadata['height']), 'Image dimensions retrieved on file_load() for an image file.');
269
    $this->assertTrue(isset($file->metadata['width']), 'Image dimensions retrieved on file_load() for an image file.');
270

  
271
    $this->assertEqual($file->metadata['height'], $image_file->metadata['height'], 'Loaded image height is equal to saved image height.');
272
    $this->assertEqual($file->metadata['width'], $image_file->metadata['width'], 'Loaded image width is equal to saved image width.');
273

  
274
    $file = file_load($text_file->fid);
275
    $this->assertFalse(isset($file->metadata['height']), 'No image height retrieved on file_load() for an text file.');
276
    $this->assertFalse(isset($file->metadata['width']), 'No image width retrieved on file_load() for an text file.');
333 277

  
334 278
    // Test hook_file_update().
335 279
    // Load the first image file and resize it.
336
    $image_files = array_keys($files);
337
    $file = file_load(reset($image_files));
338
    $image = image_load($file->uri);
339
    image_resize($image, $file->metadata['width'] / 2, $file->metadata['height'] / 2);
280
    $height = $image_file->metadata['width'] / 2;
281
    $width = $image_file->metadata['height'] / 2;
282
    $image = image_load($image_file->uri);
283
    image_resize($image, $width, $height);
340 284
    image_save($image);
341
    file_save($file);
342
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Image file height updated by file_save().');
343
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Image file width updated by file_save().');
285
    file_save($image_file);
286

  
287
    $this->assertEqual($image_file->metadata['height'], $height, 'Image file height updated by file_save().');
288
    $this->assertEqual($image_file->metadata['width'], $width, 'Image file width updated by file_save().');
289

  
344 290
    // Clear the cache and reload the file.
345 291
    entity_get_controller('file')->resetCache();
346
    $file = file_load($file->fid);
347
    $this->assertEqual($file->metadata['height'], $files[$file->fid]['height'] / 2, 'Updated image height retrieved by file_load().');
348
    $this->assertEqual($file->metadata['width'], $files[$file->fid]['width'] / 2, 'Updated image width retrieved by file_load().');
349 292

  
350
    //Test hook_file_delete().
293
    $file = file_load($image_file->fid);
294
    $this->assertEqual($file->metadata['height'], $height, 'Updated image height retrieved by file_load().');
295
    $this->assertEqual($file->metadata['width'], $width, 'Updated image width retrieved by file_load().');
296

  
297
    // Verify that the image dimension metadata is removed on file deletion.
351 298
    file_delete($file, TRUE);
352
    $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => 'fid'))->fetchField(), 'Row deleted in {file_dimensions} on file_delete().');
299
    $this->assertFalse(db_query('SELECT COUNT(*) FROM {file_metadata} WHERE fid = :fid', array(':fid' => 'fid'))->fetchField(), 'Row deleted in {file_metadata} on file_delete().');
353 300
  }
354 301
}
355 302

  
303
/**
304
 * Tests editing existing file entities.
305
 */
356 306
class FileEntityEditTestCase extends FileEntityTestHelper {
357 307
  protected $web_user;
358 308
  protected $admin_user;
......
463 413
  }
464 414
}
465 415

  
466
class FileEntityCreationTestCase extends FileEntityTestHelper {
416
/**
417
 * Tests creating new file entities through the file upload wizard.
418
 */
419
class FileEntityUploadWizardTestCase extends FileEntityTestHelper {
467 420
  public static function getInfo() {
468 421
    return array(
469
      'name' => 'File entity creation',
470
      'description' => 'Create a file and test saving it.',
422
      'name' => 'File entity upload wizard',
423
      'description' => 'Upload a file using the multi-step wizard.',
471 424
      'group' => 'File entity',
425
      'dependencies' => array('token'),
472 426
    );
473 427
  }
474 428

  
475 429
  function setUp() {
476
    parent::setUp();
430
    parent::setUp('token');
477 431

  
478
    $web_user = $this->drupalCreateUser(array('create files', 'edit own document files'));
432
    // Disable the private file system which is automatically enabled by
433
    // DrupalTestCase so we can test the upload wizard correctly.
434
    variable_del('file_private_path');
435

  
436
    $web_user = $this->drupalCreateUser(array('create files', 'view own private files'));
479 437
    $this->drupalLogin($web_user);
480 438
  }
481 439

  
482 440
  /**
483
   * Create a "document" file and verify its consistency in the database.
441
   * Test the basic file upload wizard functionality.
484 442
   */
485
  function testFileEntityCreation() {
443
  function testFileEntityUploadWizardBasic() {
486 444
    $test_file = $this->getTestFile('text');
487
    // Create a file.
445

  
446
    // Step 1: Upload a basic document file.
488 447
    $edit = array();
489 448
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
490 449
    $this->drupalPost('file/add', $edit, t('Next'));
491 450

  
492
    // Step 2: Scheme selection
493
    if ($this->xpath('//input[@name="scheme"]')) {
494
      $this->drupalPost(NULL, array(), t('Next'));
495
    }
451
    // Check that the file exists in the database.
452
    $fid = $this->getLastFileId();
453
    $file = file_load($fid);
454
    $this->assertTrue($file, t('File found in database.'));
496 455

  
497 456
    // Check that the document file has been uploaded.
498
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $test_file->filename)), t('Document file uploaded.'));
457
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $file->filename)), t('Document file uploaded.'));
458
  }
459

  
460
  /**
461
   * Test the file upload wizard type step.
462
   */
463
  function testFileEntityUploadWizardTypes() {
464
    $test_file = $this->getTestFile('text');
465

  
466
    // Create multiple file types with the same mime types.
467
    $this->createFileType(array('type' => 'document1', 'label' => 'Document 1', 'mimetypes' => array('text/plain')));
468
    $this->createFileType(array('type' => 'document2', 'label' => 'Document 2', 'mimetypes' => array('text/plain')));
469

  
470
    // Step 1: Upload a basic document file.
471
    $edit = array();
472
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
473
    $this->drupalPost('file/add', $edit, t('Next'));
474

  
475
    // Step 2: File type selection.
476
    $edit = array();
477
    $edit['type'] = 'document2';
478
    $this->drupalPost(NULL, $edit, t('Next'));
499 479

  
500 480
    // Check that the file exists in the database.
501
    $file = $this->getFileByFilename($test_file->filename);
481
    $fid = $this->getLastFileId();
482
    $file = file_load($fid);
483
    $this->assertTrue($file, t('File found in database.'));
484

  
485
    // Check that the document file has been uploaded.
486
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document 2', '%name' => $file->filename)), t('Document 2 file uploaded.'));
487
  }
488

  
489
  /**
490
   * Test the file upload wizard scheme step.
491
   */
492
  function testFileEntityUploadWizardSchemes() {
493
    $test_file = $this->getTestFile('text');
494

  
495
    // Enable the private file system.
496
    variable_set('file_private_path', $this->private_files_directory);
497

  
498
    // Step 1: Upload a basic document file.
499
    $edit = array();
500
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
501
    $this->drupalPost('file/add', $edit, t('Next'));
502

  
503
    // Step 3: Scheme selection.
504
    $edit = array();
505
    $edit['scheme'] = 'private';
506
    $this->drupalPost(NULL, $edit, t('Next'));
507

  
508
    // Check that the file exists in the database.
509
    $fid = $this->getLastFileId();
510
    $file = file_load($fid);
511
    $this->assertTrue($file, t('File found in database.'));
512

  
513
    // Check that the document file has been uploaded.
514
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Document', '%name' => $file->filename)), t('Document file uploaded.'));
515
  }
516

  
517
  /**
518
   * Test the file upload wizard field step.
519
   */
520
  function testFileEntityUploadWizardFields() {
521
    $test_file = $this->getTestFile('image');
522
    $filename = $this->randomName();
523
    $alt = $this->randomName();
524
    $title = $this->randomName();
525

  
526
    // Step 1: Upload a basic image file.
527
    $edit = array();
528
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
529
    $this->drupalPost('file/add', $edit, t('Next'));
530

  
531
    // Step 4: Attached fields.
532
    $edit = array();
533
    $edit['filename'] = $filename;
534
    $edit['field_file_image_alt_text[' . LANGUAGE_NONE . '][0][value]'] = $alt;
535
    $edit['field_file_image_title_text[' . LANGUAGE_NONE . '][0][value]'] = $title;
536
    $this->drupalPost(NULL, $edit, t('Save'));
537

  
538
    // Check that the file exists in the database.
539
    $fid = $this->getLastFileId();
540
    $file = file_load($fid);
502 541
    $this->assertTrue($file, t('File found in database.'));
542

  
543
    // Check that the image file has been uploaded.
544
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $filename)), t('Image file uploaded.'));
545

  
546
    // Check that the alt and title text was loaded from the fields.
547
    $this->assertEqual($file->alt, $alt, t('Alt text was stored as file metadata.'));
548
    $this->assertEqual($file->title, $title, t('Title text was stored as file metadata.'));
549
  }
550

  
551
  /**
552
   * Test skipping each of the file upload wizard steps.
553
   */
554
  function testFileEntityUploadWizardStepSkipping() {
555
    $test_file = $this->getTestFile('image');
556
    $filename = $this->randomName();
557

  
558
    // Ensure that the file is affected by every step.
559
    variable_set('file_private_path', $this->private_files_directory);
560

  
561
    $this->createFileType(array('type' => 'image1', 'label' => 'Image 1', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
562
    $this->createFileType(array('type' => 'image2', 'label' => 'Image 2', 'mimetypes' => array('image/jpeg', 'image/gif', 'image/png', 'image/tiff')));
563

  
564
    $field_name = drupal_strtolower($this->randomName() . '_field_name');
565
    $field = array('field_name' => $field_name, 'type' => 'text');
566
    field_create_field($field);
567
    $instance = array(
568
      'field_name' => $field_name,
569
      'entity_type' => 'file',
570
      'bundle' => 'image2',
571
      'label' => $this->randomName() . '_label',
572
    );
573
    field_create_instance($instance);
574

  
575
    // Test skipping each upload wizard step.
576
    foreach (array('types', 'schemes', 'fields') as $step) {
577
      // Step to skip.
578
      switch ($step) {
579
        case 'types':
580
          variable_set('file_entity_file_upload_wizard_skip_file_type', TRUE);
581
          break;
582
        case 'schemes':
583
          variable_set('file_entity_file_upload_wizard_skip_scheme', TRUE);
584
          break;
585
        case 'fields':
586
          variable_set('file_entity_file_upload_wizard_skip_fields', TRUE);
587
          break;
588
      }
589

  
590
      // Step 1: Upload a basic image file.
591
      $edit = array();
592
      $edit['files[upload]'] = drupal_realpath($test_file->uri);
593
      $this->drupalPost('file/add', $edit, t('Next'));
594

  
595
      // Step 2: File type selection.
596
      if ($step != 'types') {
597
        $edit = array();
598
        $edit['type'] = 'image2';
599
        $this->drupalPost(NULL, $edit, t('Next'));
600
      }
601

  
602
      // Step 3: Scheme selection.
603
      if ($step != 'schemes') {
604
        $edit = array();
605
        $edit['scheme'] = 'private';
606
        $this->drupalPost(NULL, $edit, t('Next'));
607
      }
608

  
609
      // Step 4: Attached fields.
610
      if ($step != 'fields') {
611
        // Skipping file type selection essentially skips this step as well
612
        // because the file will not be assigned a type so no fields will be
613
        // available.
614
        if ($step != 'types') {
615
          $edit = array();
616
          $edit['filename'] = $filename;
617
          $edit[$field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName();
618
          $this->drupalPost(NULL, $edit, t('Save'));
619
        }
620
      }
621

  
622
      // Check that the file exists in the database.
623
      $fid = $this->getLastFileId();
624
      $file = file_load($fid);
625
      $this->assertTrue($file, t('File found in database.'));
626

  
627
      // Determine the file's file type.
628
      $type = file_type_load($file->type);
629

  
630
      // Check that the image file has been uploaded.
631
      $this->assertRaw(t('!type %name was uploaded.', array('!type' => $type->label, '%name' => $file->filename)), t('Image file uploaded.'));
632

  
633
      // Reset 'skip' variables.
634
      variable_del('file_entity_file_upload_wizard_skip_file_type');
635
      variable_del('file_entity_file_upload_wizard_skip_scheme');
636
      variable_del('file_entity_file_upload_wizard_skip_fields');
637
    }
503 638
  }
504 639
}
505 640

  
......
585 720
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
586 721
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
587 722

  
588
    // Verify view, edit, and delete links for any file.
723
    // Verify view, usage, edit, and delete links for any file.
589 724
    $this->drupalGet('admin/content/file');
590 725
    $this->assertResponse(200);
591 726
    foreach ($files as $file) {
592 727
      $this->assertLinkByHref('file/' . $file->fid);
728
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
593 729
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
594 730
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
595 731
      // Verify tableselect.
......
646 782
    $this->assertResponse(200);
647 783
    foreach ($files as $file) {
648 784
      $this->assertLinkByHref('file/' . $file->fid);
785
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
649 786
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
650 787
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
651 788
    }
......
657 794
    $this->assertResponse(200);
658 795
    foreach ($files as $file) {
659 796
      $this->assertLinkByHref('file/' . $file->fid);
797
      $this->assertLinkByHref('file/' . $file->fid . '/usage');
660 798
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
661 799
      $this->assertLinkByHref('file/' . $file->fid . '/delete');
662 800
    }
663 801
  }
664 802
}
665 803

  
666
class FileEntityReplaceTestCase extends FileEntityTestHelper {
804
/**
805
 * Tests the file usage page.
806
 */
807
class FileEntityUsageTestCase extends FileEntityTestHelper {
808
  public static function getInfo() {
809
    return array(
810
      'name' => 'File entity usage',
811
      'description' => 'Create a file and verify its usage.',
812
      'group' => 'File entity',
813
    );
814
  }
815

  
816
  function setUp() {
817
    parent::setUp();
818

  
819
    $web_user = $this->drupalCreateUser(array('create files', 'bypass file access', 'edit own article content'));
820
    $this->drupalLogin($web_user);
821
  }
822

  
823
  /**
824
   * Create a file and verify its usage information.
825
   */
826
  function testFileEntityUsagePage() {
827
    $image_field = 'field_image';
828
    $image = $this->getTestFile('image');
829

  
830
    // Create a node, save it, then edit it to upload a file.
831
    $edit = array(
832
      "files[" . $image_field . "_" . LANGUAGE_NONE . "_0]" => drupal_realpath($image->uri),
833
    );
834
    $node = $this->drupalCreateNode(array('type' => 'article'));
835
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
836

  
837
    // Load the uploaded file.
838
    $fid = $this->getLastFileId();
839
    $file = file_load($fid);
840

  
841
    // View the file's usage page.
842
    $this->drupalGet('file/' . $file->fid . '/usage');
843

  
844
    // Verify that a link to the entity is available.
845
    $this->assertLink($node->title);
846
    $this->assertLinkByHref('node/' . $node->nid);
847

  
848
    // Verify that the entity type and use count information is also present.
849
    $expected_values = array(
850
      'type' => 'node',
851
      'count' => 1,
852
    );
853
    foreach ($expected_values as $name => $value) {
854
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
855
    }
856

  
857
    // Add a reference to the file from the same entity but registered by a
858
    // different module to ensure that the usage count is incremented and no
859
    // additional table rows are created.
860
    file_usage_add($file, 'example_module', 'node', $node->nid, 2);
861

  
862
    // Reload the page and verify that the expected values are present.
863
    $this->drupalGet('file/' . $file->fid . '/usage');
864
    $expected_values['count'] = 3;
865
    foreach ($expected_values as $name => $value) {
866
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
867
    }
868

  
869
    // Add a reference to the file from an entity that doesn't exist to ensure
870
    // that this case is handled.
871
    file_usage_add($file, 'test_module', 'imaginary', 1);
872

  
873
    // Reload the page.
874
    $this->drupalGet('file/' . $file->fid . '/usage');
875

  
876
    // Verify that the module name is used in place of a link to the entity.
877
    $this->assertNoLink('test_module');
878
    $this->assertRaw('test_module', 'Module name used in place of link to the entity.');
879

  
880
    // Verify that the entity type and use count information is also present.
881
    $expected_values = array(
882
      'type' => 'imaginary',
883
      'count' => 1,
884
    );
885
    foreach ($expected_values as $name => $value) {
886
      $this->assertTrue($this->xpath('//table/tbody/tr/td[normalize-space(text())=:text]', array(':text' => $value)), t('File usage @name was found in the table.', array('@name' => $name)));
887
    }
888
  }
889
}
890

  
891
/**
892
 * Tests image alt and title text.
893
 */
894
class FileEntityAltTitleTestCase extends FileEntityTestHelper {
895
  public static function getInfo() {
896
    return array(
897
      'name' => 'File entity alt and title text',
898
      'description' => 'Create an image file with alt and title text.',
899
      'group' => 'File entity',
900
      'dependencies' => array('token'),
901
    );
902
  }
903

  
904
  function setUp() {
905
    parent::setUp('token');
906

  
907
    $web_user = $this->drupalCreateUser(array('create files', 'edit own image files'));
908
    $this->drupalLogin($web_user);
909
  }
910

  
911
  /**
912
   * Create an "image" file and verify its associated alt and title text.
913
   */
914
  function testFileEntityAltTitle() {
915
    $test_file = $this->getTestFile('image');
916
    $alt_field_name = 'field_file_image_alt_text'; // Name of the default alt text field added to the image file type.
917
    $title_field_name = 'field_file_image_title_text'; // Name of the default title text field added to the image file type.
918

  
919
    // Create a file.
920
    $edit = array();
921
    $edit['files[upload]'] = drupal_realpath($test_file->uri);
922
    $this->drupalPost('file/add', $edit, t('Next'));
923

  
924
    // Step 2: Scheme selection.
925
    if ($this->xpath('//input[@name="scheme"]')) {
926
      $this->drupalPost(NULL, array(), t('Next'));
927
    }
928

  
929
    // Step 3: Attached fields.
930
    $alt = 'Quote" Amp& ' . 'Файл для тестирования ' . $this->randomName(); // Generate alt text containing HTML entities, spaces and non-latin characters.
931
    $title = 'Quote" Amp& ' . 'Файл для тестирования ' . $this->randomName(); // Generate title text containing HTML entities, spaces and non-latin characters.
932

  
933
    $edit = array();
934
    $edit[$alt_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $alt;
935
    $edit[$title_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $title;
936
    $this->drupalPost(NULL, $edit, t('Save'));
937

  
938
    // Check that the image file has been uploaded.
939
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $test_file->filename)), t('Image file uploaded.'));
940

  
941
    // Check that the file exists in the database.
942
    $file = $this->getFileByFilename($test_file->filename);
943
    $this->assertTrue($file, t('File found in database.'));
944

  
945
    // Check that the alt and title text was loaded from the fields.
946
    $this->assertEqual($file->alt, $alt, t('Alt text was stored as file metadata.'));
947
    $this->assertEqual($file->title, $title, t('Title text was stored as file metadata.'));
948

  
949
    // Verify that the alt and title text is present on the page.
950
    $image_info = array(
951
      'path' => $file->uri,
952
      'alt' => $alt,
953
      'title' => $title,
954
      'width' => $file->width,
955
      'height' => $file->height,
956
    );
957
    $default_output = theme('image', $image_info);
958
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
959

  
960
    // Verify that the alt and title text can be edited.
961
    $new_alt = $this->randomName();
962
    $new_title = $this->randomName();
963

  
964
    $edit = array();
965
    $edit[$alt_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $new_alt;
966
    $edit[$title_field_name . '[' . LANGUAGE_NONE . '][0][value]'] = $new_title;
967
    $this->drupalPost('file/' . $file->fid . '/edit', $edit, t('Save'));
968

  
969
    $image_info = array(
970
      'path' => $file->uri,
971
      'alt' => $new_alt,
972
      'title' => $new_title,
973
      'width' => $file->width,
974
      'height' => $file->height,
975
    );
976
    $default_output = theme('image', $image_info);
977
    $this->assertRaw($default_output, 'Image displayed using updated alt and title attributes.');
978
  }
979
}
980

  
981
/**
982
 * Tests replacing the file associated with a file entity.
983
 */
984
class FileEntityReplaceTestCase extends FileEntityTestHelper {
667 985
  public static function getInfo() {
668 986
    return array(
669 987
      'name' => 'File replacement',
......
674 992

  
675 993
  function setUp() {
676 994
    parent::setUp();
677
    $this->setUpFiles();
678 995
  }
679 996

  
680 997
  /**
......
683 1000
   */
684 1001
  function testReplaceFile() {
685 1002
    // Select the first text test file to use.
686
    $file = reset($this->files['text']);
1003
    $file = $this->createFileEntity(array('type' => 'document'));
687 1004

  
688 1005
    // Create a user with file edit permissions.
689 1006
    $user = $this->drupalCreateUser(array('edit any document files'));
......
697 1014
    $this->drupalPost(NULL, array(), t('Save'));
698 1015
    $this->assertText(t('Document @file has been updated.', array('@file' => $file->filename)), 'File was updated without file upload.');
699 1016

  
700
    // Get the next text file to use as a replacement.
1017
    // Get a text file to use as a replacement.
701 1018
    $original = clone $file;
702
    $replacement = next($this->files['text']);
1019
    $replacement = $this->getTestFile('text');
703 1020

  
704 1021
    // Test that the file saves when uploading a replacement file.
705 1022
    $edit = array();
......
718 1035
    $this->assertFalse(entity_load('file', FALSE, array('status' => 0)), 'Temporary file used for replacement was deleted.');
719 1036

  
720 1037
    // Get an image file.
721
    $image = reset($this->files['image']);
1038
    $image = $this->getTestFile('image');
722 1039
    $edit['files[replace_upload]'] = drupal_realpath($image->uri);
723 1040

  
724 1041
    // Test that validation works by uploading a non-text file as a replacement.
......
745 1062
  }
746 1063
}
747 1064

  
1065
/**
1066
 * Tests file entity tokens.
1067
 */
748 1068
class FileEntityTokenTestCase extends FileEntityTestHelper {
749 1069
  public static function getInfo() {
750 1070
    return array(
......
756 1076

  
757 1077
  function setUp() {
758 1078
    parent::setUp();
759
    $this->setUpFiles();
760 1079
  }
761 1080

  
762 1081
  function testFileEntityTokens() {
1082
    $file = $this->createFileEntity(array('type' => 'document'));
763 1083
    $tokens = array(
764 1084
      'type' => 'Document',
765 1085
      'type:name' => 'Document',
766 1086
      'type:machine-name' => 'document',
767
      'type:count' => count($this->files['text']),
1087
      'type:count' => 1,
768 1088
    );
769
    $this->assertTokens('file', array('file' => $this->files['text'][0]), $tokens);
1089
    $this->assertTokens('file', array('file' => $file), $tokens);
770 1090

  
1091
    $file = $this->createFileEntity(array('type' => 'image'));
771 1092
    $tokens = array(
772 1093
      'type' => 'Image',
773 1094
      'type:name' => 'Image',
774 1095
      'type:machine-name' => 'image',
775
      'type:count' => count($this->files['image']),
1096
      'type:count' => 1,
776 1097
    );
777
    $this->assertTokens('file', array('file' => $this->files['image'][0]), $tokens);
1098
    $this->assertTokens('file', array('file' => $file), $tokens);
778 1099
  }
779 1100

  
780 1101
  function assertTokens($type, array $data, array $tokens, array $options = array()) {
......
799 1120
  }
800 1121
}
801 1122

  
1123
/**
1124
 * Tests adding support for bundles to the core 'file' entity.
1125
 */
802 1126
class FileEntityTypeTestCase extends FileEntityTestHelper {
803 1127
  public static function getInfo() {
804 1128
    return array(
......
810 1134

  
811 1135
  function setUp() {
812 1136
    parent::setUp();
813
    $this->setUpFiles();
814 1137
  }
815 1138

  
816 1139
  /**
......
836 1159
    $this->assertEqual($loaded_type->label, $type_machine_label, "Was able to create a type and retreive it.");
837 1160
  }
838 1161

  
839

  
840
  /**
841
   * Ensures that the weight is respected when types are created.
842
   * @return unknown_type
843
   */
844
  function testOrder() {
845
//    $type = $this->createFileType(array('name' => 'last', 'label' => 'Last', 'weight' => 100));
846
//    $type = $this->createFileType(array('name' => 'first', 'label' => 'First'));
847
//    $types = media_type_get_types();
848
//    $keys = array_keys($types);
849
//    $this->assertTrue(isset($types['last']) && isset($types['first']), "Both types saved");
850
//    $this->assertTrue(array_search('last', $keys) > array_search('first', $keys), 'Type which was supposed to be first came first');
851
  }
852

  
853
  /**
854
   * Test view mode assignment.  Currently fails, don't know why.
855
   * @return unknown_type
856
   */
857
  function testViewModesAssigned() {
858
  }
859

  
860
  /**
861
   * Make sure candidates are presented in the case of multiple
862
   * file types.
863
   */
864
  function testTypeWithCandidates() {
865
    // Create multiple file types with the same mime types.
866
    $types = array(
867
      'image1' => $this->createFileType(array('type' => 'image1', 'label' => 'Image 1')),
868
      'image2' => $this->createFileType(array('type' => 'image2', 'label' => 'Image 2'))
869
    );
870

  
871
    // Attach a text field to one of the file types.
872
    $field = array(
873
      'field_name' => drupal_strtolower($this->randomName()),
874
      'type' => 'text',
875
      'settings' => array(
876
        'max_length' => 255,
877
      )
878
    );
879
    field_create_field($field);
880
    $instance = array(
881
      'field_name' => $field['field_name'],
882
      'entity_type' => 'file',
883
      'bundle' => 'image2',
884
      'widget' => array(
885
        'type' => 'text_textfield',
886
      ),
887
      'display' => array(
888
        'default' => array(
889
          'type' => 'text_default',
890
        ),
891
      ),
892
    );
893
    field_create_instance($instance);
894

  
895
    // Create a user with file creation access.
896
    $user = $this->drupalCreateUser(array('create files'));
897
    $this->drupalLogin($user);
898

  
899
    // Step 1: Upload file
900
    $file = reset($this->files['image']);
901
    $edit = array();
902
    $edit['files[upload]'] = drupal_realpath($file->uri);
903
    $this->drupalPost('file/add', $edit, t('Next'));
904

  
905
    // Step 2: Select file type candidate
906
    $this->assertText('Image 1', 'File type candidate list item found.');
907
    $this->assertText('Image 2', 'File type candidate list item found.');
908
    $edit = array();
909
    $edit['type'] = 'image2';
910
    $this->drupalPost(NULL, $edit, t('Next'));
911

  
912
    // Step 3: Select file scheme candidate
913
    $this->assertText('Public local files served by the webserver.', 'File scheme candidate list item found.');
914
    $this->assertText('Private local files served by Drupal.', 'File scheme candidate list item found.');
915
    $edit = array();
916
    $edit['scheme'] = 'public';
917
    $this->drupalPost(NULL, $edit, t('Next'));
918

  
919
    // Step 4: Complete field widgets
920
    $langcode = LANGUAGE_NONE;
921
    $edit = array();
922
    $edit["{$field['field_name']}[$langcode][0][value]"] = $this->randomName();
923
    $this->drupalPost(NULL, $edit, t('Save'));
924
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image 2', '%name' => $file->filename)), t('Image 2 file updated.'));
925
    $this->assertText($field['field_name'], 'File text field was found.');
926
  }
927

  
928
  /**
929
   * Make sure no candidates appear when only one mime type is available.
930
   * NOTE: Depends on file_entity.module default 'image' type.
931
   */
932
  function testTypeWithoutCandidates() {
933
    // Attach a text field to the default image file type.
934
    $field = array(
935
      'field_name' => drupal_strtolower($this->randomName()),
936
      'type' => 'text',
937
      'settings' => array(
938
        'max_length' => 255,
939
      )
940
    );
941
    field_create_field($field);
942
    $instance = array(
943
      'field_name' => $field['field_name'],
944
      'entity_type' => 'file',
945
      'bundle' => 'image',
946
      'widget' => array(
947
        'type' => 'text_textfield',
948
      ),
949
      'display' => array(
950
        'default' => array(
951
          'type' => 'text_default',
952
        ),
953
      ),
954
    );
955
    field_create_instance($instance);
956

  
957
    // Create a user with file creation access.
958
    $user = $this->drupalCreateUser(array('create files'));
959
    $this->drupalLogin($user);
960

  
961
    // Step 1: Upload file
962
    $file = reset($this->files['image']);
963
    $edit = array();
964
    $edit['files[upload]'] = drupal_realpath($file->uri);
965
    $this->drupalPost('file/add', $edit, t('Next'));
966

  
967
    // Step 2: Scheme selection
968
    if ($this->xpath('//input[@name="scheme"]')) {
969
      $this->drupalPost(NULL, array(), t('Next'));
970
    }
971

  
972
    // Step 3: Complete field widgets
973
    $langcode = LANGUAGE_NONE;
974
    $edit = array();
975
    $edit["{$field['field_name']}[$langcode][0][value]"] = $this->randomName();
976
    $this->drupalPost(NULL, $edit, t('Save'));
977
    $this->assertRaw(t('!type %name was uploaded.', array('!type' => 'Image', '%name' => $file->filename)), t('Image file uploaded.'));
978
    $this->assertText($field['field_name'], 'File text field was found.');
979
  }
980

  
981 1162
  /**
982 1163
   * Test file types CRUD UI.
983 1164
   */
......
1067 1248
  }
1068 1249
}
1069 1250

  
1251
/**
1252
 * Tests the file entity access API.
1253
 */
1070 1254
class FileEntityAccessTestCase extends FileEntityTestHelper {
1071 1255

  
1072 1256
  public static function getInfo() {
......
1079 1263

  
1080 1264
  function setUp() {
1081 1265
    parent::setUp();
1082
    $this->setUpFiles(array('uid' => 0));
1083 1266

  
1084
    // Unset the fact that file_entity_install() adds the 'view files'
1085
    // permission to all user roles. This messes with being able to fully unit
1086
    // test the file_entity_access() function.
1267
    // Remove the "view files" permission which is set by default for all users
1268
    // so we can test this permission correctly.
1087 1269
    $roles = user_roles();
1088 1270
    foreach ($roles as $rid => $role) {
1089 1271
      user_role_revoke_permissions($rid, array('view files'));
1090 1272
    }
1091 1273
  }
1092 1274

  
1093
  /**
1094
   * Asserts file_entity_access correctly grants or denies access.
1095
   */
1096
  function assertFileEntityAccess($ops, $file, $account) {
1097
    drupal_static_reset('file_entity_access');
1098
    foreach ($ops as $op => $result) {
1099
      $msg = t("file_entity_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
1100
      $this->assertEqual($result, file_entity_access($op, $file, $account), $msg);
1101
    }
1102
  }
1103

  
1104 1275
  /**
1105 1276
   * Runs basic tests for file_entity_access function.
1106 1277
   */
1107 1278
  function testFileEntityAccess() {
1108
    $file = reset($this->files['image']);
1279
    $file = $this->createFileEntity(array('type' => 'image'));
1109 1280

  
1110 1281
    // Ensures user with 'bypass file access' permission can do everything.
1111 1282
    $web_user = $this->drupalCreateUser(array('bypass file access'));
......
1164 1335
  }
1165 1336

  
1166 1337
  /**
1167
   * Test to see if we have access to view files when granted the permissions.
1168
   * In this test we aim to prove the permissions work in the following pages:
1338
   * Tests page access.
1339
   *
1340
   * Verifies the privileges required to access the following pages:
1169 1341
   *  file/add
1170 1342
   *  file/%/view
1171 1343
   *  file/%/download
1172 1344
   *  file/%/edit
1345
   *  file/%/usage
1173 1346
   *  file/%/delete
1174 1347
   */
1175 1348
  function testFileEntityPageAccess() {
1176
    $web_user = $this->drupalCreateUser(array());
1349
    // Test creating files without permission.
1350
    $web_user = $this->drupalCreateUser();
1177 1351
    $this->drupalLogin($web_user);
1178 1352
    $this->drupalGet('file/add');
1179 1353
    $this->assertResponse(403, 'Users without access can not access the file add page');
1180
    $web_user = $this->drupalCreateUser(array('create files'));
1181
    $this->drupalLogin($web_user);
1354

  
1355
    // Test creating files with permission.
1356
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1357
      'create files' => TRUE,
1358
    ));
1182 1359
    $this->drupalGet('file/add');
1183 1360
    $this->assertResponse(200, 'Users with access can access the file add page');
1184 1361

  
1185
    $file = reset($this->files['text']);
1362
    $file = $this->createFileEntity(array('type' => 'document','uid' => $web_user->uid));
1186 1363

  
1187
    // This fails.. No clue why but, tested manually and works as should.
1188
    //$web_user = $this->drupalCreateUser(array('view own files'));
1189
    //$this->drupalLogin($web_user);
1190
    //$this->drupalGet("file/{$file->fid}/view");
1191
    //$this->assertResponse(403, 'Users without access can not access the file view page');
1192
    $web_user = $this->drupalCreateUser(array('view files'));
1193
    $this->drupalLogin($web_user);
1364
    // Test viewing own files without permission.
1365
    $this->drupalGet("file/{$file->fid}/view");
1366
    $this->assertResponse(403, 'Users without access can not view their own files');
1367

  
1368
    // Test viewing own files with permission.
1369
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1370
      'view own files' => TRUE,
1371
    ));
1372
    $this->drupalGet("file/{$file->fid}/view");
1373
    $this->assertResponse(200, 'Users with access can view their own files');
1374

  
1375
    // Test viewing any files without permission.
1376
    $file->uid = 1;
1377
    file_save($file);
1378
    $this->drupalGet("file/{$file->fid}/view");
1379
    $this->assertResponse(403, 'Users with access can not view any file');
1380

  
1381
    // Test viewing any files with permission.
1382
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1383
      'view files' => TRUE,
1384
    ));
1194 1385
    $this->drupalGet("file/{$file->fid}/view");
1195
    $this->assertResponse(200, 'Users with access can access the file view page');
1386
    $this->assertResponse(200, 'Users with access can view any file');
1196 1387

  
1388
    // Test downloading own files without permission.
1389
    $file->uid = $web_user->uid;
1390
    file_save($file);
1197 1391
    $url = "file/{$file->fid}/download";
1198
    $web_user = $this->drupalCreateUser(array());
1199
    $this->drupalLogin($web_user);
1200 1392
    $this->drupalGet($url, array('query' => array('token' => file_entity_get_download_token($file))));
1201
    $this->assertResponse(403, 'Users without access can not download the file');
1202
    $web_user = $this->drupalCreateUser(array('download any document files'));
1203
    $this->drupalLogin($web_user);
1393
    $this->assertResponse(403, 'Users without access can not download their own files');
1394

  
1395
    // Test downloading own files with permission.
1396
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1397
      'download own document files' => TRUE,
1398
    ));
1399
    $this->drupalGet($url, array('query' => array('token' => file_entity_get_download_token($file))));
1400
    $this->assertResponse(200, 'Users with access can download their own files');
1401

  
1402
    // Test downloading any files without permission.
1403
    $file->uid = 1;
1404
    file_save($file);
1405
    $url = "file/{$file->fid}/download";
1204 1406
    $this->drupalGet($url, array('query' => array('token' => file_entity_get_download_token($file))));
1205
    $this->assertResponse(200, 'Users with access can download the file');
1407
    $this->assertResponse(403, 'Users without access can not download any file');
1408

  
1409
    // Test downloading any files with permission.
1410
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1411
      'download any document files' => TRUE,
1412
    ));
1413
    $this->drupalGet($url, array('query' => array('token' => file_entity_get_download_token($file))));
1414
    $this->assertResponse(200, 'Users with access can download any file');
1415

  
1416
    // Test downloading files with an invalid token.
1206 1417
    $this->drupalGet($url, array('query' => array('token' => 'invalid-token')));
1207
    $this->assertResponse(403, 'Cannot download file with in invalid token.');
1418
    $this->assertResponse(403, 'Cannot download file with an invalid token.');
1419

  
1420
    // Test downloading files without a token.
1208 1421
    $this->drupalGet($url);
1209 1422
    $this->assertResponse(403, 'Cannot download file without a token.');
1210 1423
    variable_set('file_entity_allow_insecure_download', TRUE);
1424

  
1425
    // Test downloading files with permission but without a token when insecure
1426
    // downloads are enabled.
1211 1427
    $this->drupalGet($url);
1212 1428
    $this->assertResponse(200, 'Users with access can download the file without a token when file_entity_allow_insecure_download is set.');
1213 1429

  
1214
    $web_user = $this->drupalCreateUser(array());
1215
    $this->drupalLogin($web_user);
1430
    // Tests editing own files without permission.
1431
    $file->uid = $web_user->uid;
1432
    file_save($file);
1216 1433
    $this->drupalGet("file/{$file->fid}/edit");
1217
    $this->assertResponse(403, 'Users without access can not access the file edit page');
1218
    $web_user = $this->drupalCreateUser(array('edit any document files'));
1219
    $this->drupalLogin($web_user);
1434
    $this->assertResponse(403, 'Users without access can not edit own files');
1435

  
1436
    // Tests checking the usage of their own files without permission.
1437
    $this->drupalGet("file/{$file->fid}/usage");
1438
    $this->assertResponse(403, 'Users without access can not check the usage of their own files');
1439

  
1440
    // Tests editing own files with permission.
1441
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1442
      'edit own document files' => TRUE,
1443
    ));
1220 1444
    $this->drupalGet("file/{$file->fid}/edit");
1221
    $this->assertResponse(200, 'Users with access can access the file add page');
1445
    $this->assertResponse(200, 'Users with access can edit own files');
1222 1446

  
1223
    $web_user = $this->drupalCreateUser(array());
1224
    $this->drupalLogin($web_user);
1447
    // Tests checking the usage of their own files without permission.
1448
    $this->drupalGet("file/{$file->fid}/usage");
1449
    $this->assertResponse(200, 'Users with access can check the usage of their own files');
1450

  
1451
    // Tests editing any files without permission.
1452
    $file->uid = 1;
1453
    file_save($file);
1454
    $this->drupalGet("file/{$file->fid}/edit");
1455
    $this->assertResponse(403, 'Users without access can not edit any file');
1456

  
1457
    // Tests checking the usage of any files without permission.
1458
    $this->drupalGet("file/{$file->fid}/usage");
1459
    $this->assertResponse(403, 'Users without access can not check the usage of any file');
1460

  
1461
    // Tests editing any files with permission.
1462
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1463
      'edit any document files' => TRUE,
1464
    ));
1465
    $this->drupalGet("file/{$file->fid}/edit");
1466
    $this->assertResponse(200, 'Users with access can edit any file');
1467

  
1468
    // Tests checking the usage of any files with permission.
1469
    $this->drupalGet("file/{$file->fid}/usage");
1470
    $this->assertResponse(200, 'Users with access can check the usage of any file');
1471

  
1472
    // Tests deleting own files without permission.
1473
    $file->uid = $web_user->uid;
1474
    file_save($file);
1225 1475
    $this->drupalGet("file/{$file->fid}/delete");
1226
    $this->assertResponse(403, 'Users without access can not access the file view page');
1227
    $web_user = $this->drupalCreateUser(array('delete any document files'));
1228
    $this->drupalLogin($web_user);
1476
    $this->assertResponse(403, 'Users without access can not delete their own files');
1477

  
1478
    // Tests deleting own files with permission.
1479
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1480
      'delete own document files' => TRUE,
1481
    ));
1229 1482
    $this->drupalGet("file/{$file->fid}/delete");
1230
    $this->assertResponse(200, 'Users with access can access the file add page');
1483
    $this->assertResponse(200, 'Users with access can delete their own files');
1484

  
1485
    // Tests deleting any files without permission.
1486
    $file->uid = 1;
1487
    file_save($file);
1488
    $this->drupalGet("file/{$file->fid}/delete");
1489
    $this->assertResponse(403, 'Users without access can not delete any file');
1490

  
1491
    // Tests deleting any files with permission.
1492
    user_role_change_permissions(DRUPAL_AUTHENTICATED_RID, array(
1493
      'delete any document files' => TRUE,
1494
    ));
1495
    $this->drupalGet("file/{$file->fid}/delete");
1496
    $this->assertResponse(200, 'Users with access can delete any file');
1231 1497
  }
1232 1498

  
1233 1499
  /**
......
1244 1510

  
1245 1511
      // Create private, permanent files owned by this user only he's an owner.
1246 1512
      if (!empty($case['owner'])) {
1247
        $file = next($this->files['text']);
1248
        $file->uid = $account->uid;
1249
        file_save($file);
1250
        $file = file_move($file, 'private://');
1513
        $file = $this->createFileEntity(array('type' => 'document', 'uid' => $account->uid, 'scheme' => 'private'));
1251 1514

  
1252 1515
        // Check if the physical file is there.
1253 1516
        $arguments = array('%name' => $file->filename, '%username' => $account->name, '%uri' => $file->uri);
......
1266 1529
      }
1267 1530
    }
1268 1531
  }
1532

  
1533
  /**
1534
   * Asserts file_entity_access correctly grants or denies access.
1535
   */
1536
  function assertFileEntityAccess($ops, $file, $account) {
1537
    drupal_static_reset('file_entity_access');
1538
    foreach ($ops as $op => $result) {
1539
      $msg = t("file_entity_access returns @result with operation '@op'.", array('@result' => $result ? 'true' : 'false', '@op' => $op));
1540
      $this->assertEqual($result, file_entity_access($op, $file, $account), $msg);
1541
    }
1542
  }
1543

  
1544
  /**
1545
   * Helper for testFileEntityPrivateDownloadAccess() test.
1546
   *
1547
   * Defines several cases for accesing private files.
1548
   *
1549
   * @return array
1550
   *   Array of associative arrays, each one having the next keys:
1551
   *   - "message" string with the assertion message.
1552
   *   - "permissions" array of permissions or NULL for anonymous user.
1553
   *   - "expect" expected HTTP response code.
1554
   *   - "owner" Optional boolean indicating if the user is a file owner.
1555
   */
1556
  function getPrivateDownloadAccessCases() {
1557
    return array(
1558
      array(
1559
        'message' => "File owners cannot download their own files unless they are granted the 'view own private files' permission.",
1560
        'permissions' => array(),
1561
        'expect' => 403,
1562
        'owner' => TRUE,
1563
      ),
1564
      array(
1565
        'message' => "File owners can download their own files as they have been granted the 'view own private files' permission.",
1566
        'permissions' => array('view own private files'),
1567
        'expect' => 200,
1568
        'owner' => TRUE,
1569
      ),
1570
      array(
1571
        'message' => "Anonymous users cannot download private files.",
1572
        'permissions' => NULL,
1573
        'expect' => 403,
1574
      ),
1575
      array(
1576
        'message' => "Authenticated users cannot download each other's private files.",
1577
        'permissions' => array(),
1578
        'expect' => 403,
1579
      ),
1580
      array(
1581
        'message' => "Users who can view public files are not able to download private files.",
1582
        'permissions' => array('view files'),
1583
        'expect' => 403,
1584
      ),
1585
      array(
1586
        'message' => "Users who bypass file access can download any file.",
1587
        'permissions' => array('bypass file access'),
1588
        'expect' => 200,
1589
      ),
1590
    );
1591
  }
1269 1592
}
1270 1593

  
1594
/**
1595
 * Tests overriding file attributes.
1596
 */
1271 1597
class FileEntityAttributeOverrideTestCase extends FileEntityTestHelper {
1272 1598

  
1273 1599
  public static function getInfo() {
......
1278 1604
    );
1279 1605
  }
1280 1606

  
1281
  function setUp() {
1282
    parent::setUp();
1283
    $this->setUpFiles();
1284
  }
1285

  
1286 1607
  /**
1287 1608
   * Test to see if file attributes can be overridden.
1288 1609
   */
......
1295 1616

  
1296 1617
    );
1297 1618

  
1298
    // Retrieve an image file entity for testing.
1299
    $file = reset($this->files['image']);
1619
    // Create an image file entity for testing.
1620
    $file = $this->createFileEntity(array('type' => 'image'));
1300 1621

  
1301 1622
    // Override a variety of attributes.
1302 1623
    foreach ($overrides as $override => $value) {
1303 1624
      $file->override['attributes'][$override] = $value;
1304 1625
    }
1305 1626

  
1306
    // Test that the attributes have been overridden.
1627
    // Build just the file portion of a file entity.
1307 1628
    $build = file_view_file($file, 'full');
1308 1629

  
1630
    // Verify that all of the overrides replaced the attributes.
1309 1631
    foreach ($overrides as $attribute => $expected_value) {
1310
      $this->assertEqual($build['#item'][$attribute], $expected_value, format_string('The %attribute was overridden correctly.', array('%attribute' => $attribute)));
1632
      $this->assertEqual($build['#file']->$attribute, $expected_value, format_string('The %attribute was overridden correctly.', array('%attribute' => $attribute)));
1311 1633
    }
1312 1634
  }
1313 1635
}

Also available in: Unified diff