summaryrefslogtreecommitdiff
path: root/sites/all/modules/media/tests/media.test
blob: 3594aaf01de9f9d9878b70d8ac69ffe6f2142a3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
<?php

/**
 * @file
 * Tests for media.module.
 */

/**
 * Provides methods specifically for testing Media module's field handling.
 */
class MediaFileFieldTestCase extends DrupalWebTestCase {
  protected $admin_user;

  function setUp() {
    // Since this is a base class for many test cases, support the same
    // flexibility that DrupalWebTestCase::setUp() has for the modules to be
    // passed in as either an array or a variable number of string arguments.
    $modules = func_get_args();
    if (isset($modules[0]) && is_array($modules[0])) {
      $modules = $modules[0];
    }
    $modules[] = 'media';
    $modules[] = 'media_module_test';
    parent::setUp($modules);
    $this->admin_user = $this->drupalCreateUser(array('access content', 'view files', 'view own files', 'access media browser', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer nodes', 'administer files', 'bypass node access', 'bypass file access'));
    $this->drupalLogin($this->admin_user);
  }

  /**
   * Retrieves a sample file of the specified type.
   */
  function getTestFile($type_name, $size = NULL) {
    // Get a file to upload.
    $file = current($this->drupalGetTestFiles($type_name, $size));

    // Add a filesize property to files as would be read by file_load().
    $file->filesize = filesize($file->uri);

    return $file;
  }

  /**
   * Creates a new file entity.
   *
   * @param $settings
   *   A list of settings that will be added to the entity defaults.
   */
  protected function createFileEntity($settings = array()) {
    $file = new stdClass();

    // Populate defaults array.
    $settings += array(
      'filepath' => 'Файл для тестирования ' . $this->randomName(), // Prefix with non-latin characters to ensure that all file-related tests work with international filenames.
      'filemime' => 'text/plain',
      'uid' => 1,
      'timestamp' => REQUEST_TIME,
      'status' => FILE_STATUS_PERMANENT,
      'contents' => "file_put_contents() doesn't seem to appreciate empty strings so let's put in some data.",
      'scheme' => file_default_scheme(),
      'type' => NULL,
    );

    $filepath = $settings['scheme'] . '://' . $settings['filepath'];

    file_put_contents($filepath, $settings['contents']);
    $this->assertTrue(is_file($filepath), t('The test file exists on the disk.'), 'Create test file');

    $file = new stdClass();
    $file->uri = $filepath;
    $file->filename = drupal_basename($file->uri);
    $file->filemime = $settings['filemime'];
    $file->uid = $settings['uid'];
    $file->timestamp = $settings['timestamp'];
    $file->filesize = filesize($file->uri);
    $file->status = $settings['status'];
    $file->type = $settings['type'];

    // The file type is used as a bundle key, and therefore, must not be NULL.
    if (!isset($file->type)) {
      $file->type = FILE_TYPE_NONE;
    }

    // If the file isn't already assigned a real type, determine what type should
    // be assigned to it.
    if ($file->type === FILE_TYPE_NONE) {
      $type = file_get_type($file);
      if (isset($type)) {
        $file->type = $type;
      }
    }

    // Write the record directly rather than calling file_save() so we don't
    // invoke the hooks.
    $this->assertNotIdentical(drupal_write_record('file_managed', $file), FALSE, t('The file was added to the database.'), 'Create test file');

    return $file;
  }

  /**
   * Creates a new file field.
   *
   * @param $name
   *   The name of the new field (all lowercase), exclude the "field_" prefix.
   * @param $type_name
   *   The node type that this field will be added to.
   * @param $field_settings
   *   A list of field settings that will be added to the defaults.
   * @param $instance_settings
   *   A list of instance settings that will be added to the instance defaults.
   * @param $widget_settings
   *   A list of widget settings that will be added to the widget defaults.
   */
  function createFileField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
    $field = array(
      'field_name' => $name,
      'type' => 'file',
      'settings' => array(),
      'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
    );
    $field['settings'] = array_merge($field['settings'], $field_settings);
    field_create_field($field);

    $this->attachFileField($name, 'node', $type_name, $instance_settings, $widget_settings);
  }

  /**
   * Attaches a file field to an entity.
   *
   * @param $name
   *   The name of the new field (all lowercase), exclude the "field_" prefix.
   * @param $entity_type
   *   The entity type this field will be added to.
   * @param $bundle
   *   The bundle this field will be added to.
   * @param $field_settings
   *   A list of field settings that will be added to the defaults.
   * @param $instance_settings
   *   A list of instance settings that will be added to the instance defaults.
   * @param $widget_settings
   *   A list of widget settings that will be added to the widget defaults.
   */
  function attachFileField($name, $entity_type, $bundle, $instance_settings = array(), $widget_settings = array()) {
    $instance = array(
      'field_name' => $name,
      'label' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
      'required' => !empty($instance_settings['required']),
      'settings' => array(),
      'widget' => array(
        'type' => 'media_generic',
        'settings' => array(),
      ),
    );
    $instance['settings'] = array_merge($instance['settings'], $instance_settings);
    $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
    field_create_instance($instance);
  }

  /**
   * Attaches a file to a node.
   */
  function attachNodeFile($file, $field_name, $nid_or_type, $new_revision = TRUE, $extras = array()) {
    $langcode = LANGUAGE_NONE;
    $edit = array(
      "title" => $this->randomName(),
      'revision' => (string) (int) $new_revision,
    );

    if (is_numeric($nid_or_type)) {
      $nid = $nid_or_type;
    }
    else {
      // Add a new node.
      $extras['type'] = $nid_or_type;
      $node = $this->drupalCreateNode($extras);
      $nid = $node->nid;
      // Save at least one revision to better simulate a real site.
      $this->drupalCreateNode(get_object_vars($node));
      $node = node_load($nid, NULL, TRUE);
      $this->assertNotEqual($nid, $node->vid, 'Node revision exists.');
    }

    // Attach a file to the node.
    $edit['media[' . $field_name . '_' . $langcode . '_0]'] = $file->fid;
    $this->drupalPost("node/$nid/edit", $edit, t('Save'));

    return $nid;
  }

  /**
   * Replaces a file within a node.
   */
  function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
    $edit = array(
      $field_name . '[' . LANGUAGE_NONE . '][0][fid]' => $file->fid,
      'revision' => (string) (int) $new_revision,
    );

    $this->drupalPost('node/' . $nid . '/edit', array(), t('Remove'));
    $this->drupalPost(NULL, $edit, t('Save'));
  }

  /**
   * Asserts that a file exists physically on disk.
   */
  function assertFileExists($file, $message = NULL) {
    $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->uri));
    $this->assertTrue(is_file($file->uri), $message);
  }

  /**
   * Asserts that a file exists in the database.
   */
  function assertFileEntryExists($file, $message = NULL) {
    entity_get_controller('file')->resetCache();
    $db_file = file_load($file->fid);
    $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
    $this->assertEqual($db_file->uri, $file->uri, $message);
  }

  /**
   * Asserts that a file does not exist on disk.
   */
  function assertFileNotExists($file, $message = NULL) {
    $message = isset($message) ? $message : format_string('File %file exists on the disk.', array('%file' => $file->uri));
    $this->assertFalse(is_file($file->uri), $message);
  }

  /**
   * Asserts that a file does not exist in the database.
   */
  function assertFileEntryNotExists($file, $message) {
    entity_get_controller('file')->resetCache();
    $message = isset($message) ? $message : format_string('File %file exists in database at the correct path.', array('%file' => $file->uri));
    $this->assertFalse(file_load($file->fid), $message);
  }

  /**
   * Asserts that a file's status is set to permanent in the database.
   */
  function assertFileIsPermanent($file, $message = NULL) {
    $message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->uri));
    $this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
  }
}

/**
 * Tests the 'media' element type.
 *
 * @todo Create a MediaFileTestCase base class and move MediaFileFieldTestCase
 *   methods that aren't related to fields into it.
 */
class MediaElementTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media element test',
      'description' => 'Tests the media element type.',
      'group' => 'Media',
    );
  }

  /**
   * Tests the media element type.
   */
  function testMedia() {
    // Check that $element['#size'] is passed to the child upload element.
    $this->drupalGet('media/test');
    $this->assertFieldByXpath('//input[@name="media[nested_media]" and @size="13"]', NULL, 'The custom #size attribute is passed to the child upload element.');

    // Perform the tests with all permutations of $form['#tree'] and
    // $element['#extended'].
    foreach (array(0, 1) as $tree) {
      foreach (array(0, 1) as $extended) {
        $test_file = $this->getTestFile('text');
        $test_file->uid = $this->admin_user->uid;
        $test_file = file_save($test_file);
        $path = 'media/test/' . $tree . '/' . $extended;
        $input_base_name = $tree ? 'nested_media' : 'media';

        // Submit without a file.
        $this->drupalPost($path, array(), t('Save'));
        $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submitted without a file.');

        // Submit a new file, without using the Attach button.
        $edit = array('media[' . $input_base_name . ']' => $test_file->fid);
        $this->drupalPost($path, $edit, t('Save'));
        $this->assertRaw(t('The file id is %fid.', array('%fid' => $test_file->fid)), 'Submit handler has correct file info.');

        // Now, test the Attach and Remove buttons, with and without Ajax.
        foreach (array(FALSE) as $ajax) {
          // Attach, then Submit.
          $this->drupalGet($path);
          $edit = array('media[' . $input_base_name . ']' => $test_file->fid);
          if ($ajax) {
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_attach_button');
          }
          else {
            $this->drupalPost(NULL, $edit, t('Attach'));
          }
          $this->drupalPost(NULL, array(), t('Save'));
          $this->assertRaw(t('The file id is %fid.', array('%fid' => $test_file->fid)), 'Submit handler has correct file info.');

          // Attach, then Remove, then Submit.
          $this->drupalGet($path);
          $edit = array('media[' . $input_base_name . ']' => $test_file->fid);
          if ($ajax) {
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_attach_button');
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
          }
          else {
            $this->drupalPost(NULL, $edit, t('Attach'));
            $this->drupalPost(NULL, array(), t('Remove'));
          }
          $this->drupalPost(NULL, array(), t('Save'));
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file attachment and removal was successful.');
        }
      }
    }
  }
}

/**
 * Test media file administration page functionality.
 */
class MediaAdminTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media file administration',
      'description' => 'Test media file administration page functionality.',
      'group' => 'Media',
    );
  }

  function setUp() {
    parent::setUp();
    // Remove the "view files" permission which is set
    // by default for all users so we can test this permission
    // correctly.
    $roles = user_roles();
    foreach ($roles as $rid => $role) {
      user_role_revoke_permissions($rid, array('view files'));
    }

    $this->base_user_1 = $this->drupalCreateUser(array('administer files'));
    $this->base_user_2 = $this->drupalCreateUser(array('administer files', 'view own private files'));
    $this->base_user_3 = $this->drupalCreateUser(array('administer files', 'view private files'));
    $this->base_user_4 = $this->drupalCreateUser(array('administer files', 'edit any document files', 'delete any document files', 'edit any image files', 'delete any image files'));
  }

  /**
   * Tests that the table sorting works on the files admin pages.
   */
  function testFilesAdminSort() {
    $i = 0;
    foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
      $this->createFileEntity(array('filepath' => $prefix . $this->randomName(6), 'timestamp' => $i));
      $i++;
    }

    // Test that the default sort by file_managed.timestamp DESC actually fires properly.
    $files_query = db_select('file_managed', 'fm')
      ->fields('fm', array('fid'))
      ->orderBy('timestamp', 'DESC')
      ->execute()
      ->fetchCol();

    $files_form = array();
    $this->drupalGet('admin/content/file/thumbnails');
    foreach ($this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]/@data-fid') as $input) {
      $files_form[] = $input;
    }
    $this->assertEqual($files_query, $files_form, 'Files are sorted in the form according to the default query.');

    // Compare the rendered HTML node list to a query for the files ordered by
    // filename to account for possible database-dependent sort order.
    $files_query = db_select('file_managed', 'fm')
      ->fields('fm', array('fid'))
      ->orderBy('filename')
      ->execute()
      ->fetchCol();

    $files_form = array();
    $this->drupalGet('admin/content/file/thumbnails', array('query' => array('sort' => 'asc', 'order' => 'Title')));
    foreach ($this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]/@data-fid') as $input) {
      $files_form[] = $input;
    }
    $this->assertEqual($files_query, $files_form, 'Files are sorted in the form the same as they are in the query.');
  }

  /**
   * Tests files overview with different user permissions.
   */
  function testFilesAdminPages() {
    $files['public_image'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
    $files['public_document'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'document'));

    // Verify view and edit links for any file.
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);
    foreach ($files as $file) {
      $this->assertLinkByHref('file/' . $file->fid);
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
      // Verify tableselect.
      $this->assertFieldByName('files[' . $file->fid . ']', '', t('Tableselect found.'));
    }

    // Verify no operation links are displayed for regular users.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_1);
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);
    $this->assertLinkByHref('file/' . $files['public_image']->fid);
    $this->assertLinkByHref('file/' . $files['public_document']->fid);
    $this->assertNoLinkByHref('file/' . $files['public_image']->fid . '/edit');
    $this->assertNoLinkByHref('file/' . $files['public_document']->fid . '/edit');

    // Verify no tableselect.
    $this->assertNoFieldByName('files[' . $files['public_image']->fid . ']', '', t('No tableselect found.'));

    // Verify private file is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_2);
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);
    $this->assertLinkByHref('file/' . $files['private_document']->fid);
    // Verify no operation links are displayed.
    $this->assertNoLinkByHref('file/' . $files['private_document']->fid . '/edit');

    // Verify user cannot see private file of other users.
    $this->assertNoLinkByHref('file/' . $files['private_image']->fid);
    $this->assertNoLinkByHref('file/' . $files['private_image']->fid . '/edit');

    // Verify no tableselect.
    $this->assertNoFieldByName('files[' . $files['private_document']->fid . ']', '', t('No tableselect found.'));

    // Verify private file is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_3);
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);

    // Verify user can see private file of other users.
    $this->assertLinkByHref('file/' . $files['private_document']->fid);
    $this->assertLinkByHref('file/' . $files['private_image']->fid);

    // Verify operation links are displayed for users with appropriate permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_4);
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);
    foreach ($files as $file) {
      $this->assertLinkByHref('file/' . $file->fid);
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
    }

    // Verify file access can be bypassed.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    $this->drupalGet('admin/content/file/thumbnails');
    $this->assertResponse(200);
    foreach ($files as $file) {
      $this->assertLinkByHref('file/' . $file->fid);
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
    }
  }
}

/**
 * Tests the media hooks.
 */
class MediaHooksTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media hooks test',
      'description' => 'Tests the Media hooks.',
      'group' => 'Media',
    );
  }

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

  /**
   * Tests that the media browser hooks.
   */
  function testMediaBrowserHooks() {
    // Enable media_module_test.module's hook_media_browser_plugin_info()
    // implementation and ensure it is working as designed.
    variable_set('media_module_test_media_browser_plugin_info', TRUE);

    $this->drupalGet('media/browser');
    $this->assertRaw(t('Media module test'), 'Custom browser plugin found.');

    // Enable media_module_test.module's hook_media_browser_plugin_info_alter()
    // implementation and ensure it is working as designed.
    variable_set('media_module_test_media_browser_plugin_info_alter', TRUE);

    $this->drupalGet('media/browser');
    $this->assertRaw(t('Altered plugin title'), 'Custom browser plugin was successfully altered.');

    // Enable media_module_test.module's hook_media_browser_plugins_alter()
    // implementation and ensure it is working as designed.
    variable_set('media_module_test_media_browser_plugins_alter', TRUE);

    $this->drupalGet('media/browser');
    $this->assertRaw(t('Altered browser plugin output.'), 'Custom browser plugin was successfully altered before being rendered.');
  }
}

/**
 * Tests the media browser 'Library' tab.
 */
class MediaBrowserLibraryTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media browser library test',
      'description' => 'Tests the media browser library tab.',
      'group' => 'Media',
    );
  }

  function setUp() {
    parent::setUp();
    $this->base_user_1 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files'));
    $this->base_user_2 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files', 'view own private files'));
    $this->base_user_3 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files', 'view private files'));
  }

  /**
   * Tests that the views sorting works on the media browser 'Library' tab.
   */
  function testFilesBrowserSort() {
    // Load only the 'Library' tab of the media browser.
    $options = array(
      'query' => array(
        'enabledPlugins' => array(
          'media_default--media_browser_1' => 'media_default--media_browser_1',
        ),
      ),
    );

    $i = 0;
    foreach (array('dd', 'aa', 'DD', 'bb', 'cc', 'CC', 'AA', 'BB') as $prefix) {
      $this->createFileEntity(array('filepath' => $prefix . $this->randomName(6), 'timestamp' => $i));
      $i++;
    }

    // Test that the default sort by file_managed.timestamp DESC actually fires properly.
    $files_query = db_select('file_managed', 'fm')
      ->fields('fm', array('fid'))
      ->orderBy('timestamp', 'DESC')
      ->execute()
      ->fetchCol();

    $files_form = array();
    $this->drupalGet('media/browser', $options);
    foreach ($this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]/@data-fid') as $input) {
      $files_form[] = $input;
    }
    $this->assertEqual($files_query, $files_form, 'Files are sorted in the form according to the default query.');
  }

  /**
   * Tests media browser 'Library' tab with different user permissions.
   */
  function testFilesBrowserLibrary() {
    // Load only the 'Library' tab of the media browser.
    $options = array(
      'query' => array(
        'enabledPlugins' => array(
          'media_default--media_browser_1' => 'media_default--media_browser_1',
        ),
      ),
    );

    $files['public_image'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
    $files['public_document'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_2->uid, 'type' => 'document'));
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_1->uid, 'type' => 'image'));
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'document'));

    // Verify all files are displayed for administrators.
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    foreach ($files as $file) {
      $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
        ':fid' => $file->fid,
      ));
      $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $file->fid)));
    }

    // Verify public files are displayed.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_1);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['public_image']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['public_image']->fid)));
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['public_document']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['public_document']->fid)));

    // Verify private file is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_2);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_document']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['private_document']->fid)));

    // Verify user cannot see private file of other users.
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_image']->fid,
    ));
    $this->assertNoFieldByXPath($xpath, TRUE, format_string('File with file ID %fid not found.', array('%fid' => $files['private_image']->fid)));

    // Verify private file is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_3);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);

    // Verify user can see private file of other users.
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_document']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['private_document']->fid)));
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_image']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['private_image']->fid)));

    // Verify file access can be bypassed.
    $this->drupalLogout();
    $this->drupalLogin($this->admin_user);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    foreach ($files as $file) {
      $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
        ':fid' => $file->fid,
      ));
      $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $file->fid)));
    }
  }
}

/**
 * Tests the media browser settings.
 */
class MediaBrowserSettingsTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media browser settings test',
      'description' => 'Tests the media browser settings.',
      'group' => 'Media',
    );
  }

  function setUp() {
    parent::setUp('file_test');
  }

  /**
   * Tests the media browser settings.
   */
  function testBrowserSettings() {
    $settings = array(
      'scheme' => array('public', 'private'),
      'type' => array('image', 'document'),
      'extension' => array('jpg', 'txt'),
    );

    // Perform the tests with unique permutations of $scheme, $type and
    // $extension.
    foreach ($settings['scheme'] as $scheme) {
      foreach ($settings['type'] as $type) {
        foreach ($settings['extension'] as $extension) {
          $file = $this->createFileEntity(array('scheme' => $scheme, 'uid' => $this->admin_user->uid, 'type' => $type, 'filemime' => media_get_extension_mimetype($extension)));

          $options = array(
            'query' => array(
              'enabledPlugins' => array(
                'media_default--media_browser_1' => 'media_default--media_browser_1',
              ),
              'schemes' => array($scheme),
              'types' => array($type),
              'file_extensions' => $extension,
            ),
          );

          // Verify that the file is displayed.
          $this->drupalGet('media/browser', $options);
          $this->assertResponse(200);
          $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
            ':fid' => $file->fid,
          ));
          $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $file->fid)));

          // Verify that no other files are also displayed.
          $files = $this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]');
          $this->assertEqual(count($files), 1, 'There is only one file that matches the current browser configuration.');
        }
      }
    }

    // Perform the tests with none and all of the restrictions.
    foreach (array('none', 'all') as $restrictions) {
      $options = array(
        'query' => array(
          'enabledPlugins' => array(
            'media_default--media_browser_1' => 'media_default--media_browser_1',
          ),
        ),
      );

      switch ($restrictions) {
        case 'none':
          $options['query']['schemes'] = array();
          $options['query']['types'] = array();
          $options['query']['file_extensions'] = array();
          break;
        case 'all':
          $options['query']['schemes'] = $settings['scheme'];
          $options['query']['types'] = $settings['type'];
          $options['query']['file_extensions'] = implode(' ', $settings['extension']);
          break;
      }

      // Verify that all of the files are displayed.
      $this->drupalGet('media/browser', $options);
      $this->assertResponse(200);
      $files = $this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]');
      $this->assertEqual(count($files), 8, format_string('All of the files were displayed when %restrictions of the restrictions were enabled.', array('%restrictions' => $restrictions)));
    }

    // Verify that extension restrictions do not affect remote files.
    $scheme = 'dummy-remote';
    $type = 'video';
    $extension = 'mp4';

    $file = $this->createFileEntity(array('scheme' => $scheme, 'uid' => $this->admin_user->uid, 'type' => $type, 'filemime' => media_get_extension_mimetype($extension)));

    $options = array(
      'query' => array(
        'enabledPlugins' => array(
          'media_default--media_browser_1' => 'media_default--media_browser_1',
        ),
        'schemes' => array($scheme, 'public'), // Include a local stream wrapper in order to trigger extension restrictions.
        'types' => array($type),
        'file_extensions' => 'fake', // Use an invalid file extension to ensure that it does not affect restrictions.
      ),
    );

    // Verify that the file is displayed.
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $file->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $file->fid)));

    // Verify that no other files are also displayed.
    $files = $this->xpath('//ul[@class="media-list-thumbnails"]/li/div[@data-fid]');
    $this->assertEqual(count($files), 1, 'There is only one file that matches the current browser configuration.');
  }
}

/**
 * Tests the media browser 'My files' tab.
 */
class MediaBrowserMyFilesTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media browser my files test',
      'description' => 'Tests the media browser my files tab.',
      'group' => 'Media',
    );
  }

  function setUp() {
    parent::setUp();
    $this->base_user_1 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files'));
    $this->base_user_2 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files', 'view own files'));
    $this->base_user_3 = $this->drupalCreateUser(array('access media browser', 'create files', 'administer files', 'view own files', 'view own private files'));
  }

  /**
   * Tests media browser 'My files' tab with different user permissions.
   */
  function testFilesBrowserMyFiles() {
    // Load only the 'My files' tab of the media browser.
    $options = array(
      'query' => array(
        'enabledPlugins' => array(
          'media_default--media_browser_my_files' => 'media_default--media_browser_my_files',
        ),
      ),
    );

    $files['public_image'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_2->uid, 'type' => 'image'));
    $files['public_document'] = $this->createFileEntity(array('scheme' => 'public', 'uid' => $this->base_user_3->uid, 'type' => 'document'));
    $files['private_image'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_2->uid, 'type' => 'image'));
    $files['private_document'] = $this->createFileEntity(array('scheme' => 'private', 'uid' => $this->base_user_3->uid, 'type' => 'document'));

    // Verify administrators do not have any special access to files.
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    foreach ($files as $file) {
      $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
        ':fid' => $file->fid,
      ));
      $this->assertNoFieldByXPath($xpath, TRUE, format_string('File with file ID %fid not found.', array('%fid' => $file->fid)));
    }

    // Verify users require the 'view own files' permission in order to access
    // the 'My files' tab.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_1);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//div[@class="media_default--media_browser_my_files"]');
    $this->assertNoFieldByXPath($xpath, TRUE, 'User with insufficient permissions was unable to view the My files tab.');

    // Verify own public files are displayed.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_2);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['public_image']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['public_image']->fid)));

    // Verify own private file is displayed with permission.
    $this->drupalLogout();
    $this->drupalLogin($this->base_user_3);
    $this->drupalGet('media/browser', $options);
    $this->assertResponse(200);
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_document']->fid,
    ));
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['private_document']->fid)));

    // Verify user cannot see files of other users.
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['public_image']->fid,
    ));
    $this->assertNoFieldByXPath($xpath, TRUE, format_string('File with file ID %fid not found.', array('%fid' => $files['public_image']->fid)));
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
      ':fid' => $files['private_image']->fid,
    ));
    $this->assertNoFieldByXPath($xpath, TRUE, format_string('File with file ID %fid not found.', array('%fid' => $files['private_image']->fid)));
  }
}

/**
 * Tests the 'media' element type settings.
 */
class MediaElementSettingsTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media element settings test',
      'description' => 'Tests the media element type JavaScript settings.',
      'group' => 'Media',
    );
  }

  /**
   * Tests the media element type settings.
   */
  function testElementSettings() {
    $form = array(
      '#type' => 'media',
    );
    drupal_render($form);
    $javascript = drupal_get_js();
    $global = array(
      'media' => array(
        'global' => array(
          'global' => array(
            'types' => array(),
            'schemes' => array(),
          ),
        ),
      ),
    );
    $settings = drupal_json_encode(drupal_array_merge_deep_array($global));
    $this->assertTrue(strpos($javascript, $settings) > 0, 'Rendered media element adds the global settings.');
  }

  /**
   * Tests the media file field widget settings.
   */
  function testWidgetSettings() {
    // Use 'page' instead of 'article', so that the 'article' image field does
    // not conflict with this test. If in the future the 'page' type gets its
    // own default file or image field, this test can be made more robust by
    // using a custom node type.
    $type_name = 'page';
    $field_name = strtolower($this->randomName());
    $this->createFileField($field_name, $type_name);
    $field = field_info_field($field_name);
    $instance = field_info_instance('node', $field_name, $type_name);

    $javascript = $this->drupalGet("node/add/$type_name");
    $field_widget = array(
        'elements' => array(
          '#edit-' . $field_name . '-' . LANGUAGE_NONE . '-0-upload' => array(
            'global' => array(
              'types' => array(
                'image' => 'image',
              ),
              'enabledPlugins' => array(),
              'schemes' => array(
                'public' => 'public',
              ),
              'file_directory' => '',
              'file_extensions' => 'txt',
              'max_filesize' => '',
              'uri_scheme' => 'public',
            ),
          ),
        ),
    );
    $settings = drupal_json_encode(drupal_array_merge_deep_array($field_widget));
    $this->assertTrue(strpos($javascript, $settings) > 0, 'Media file field widget adds element-specific settings.');
  }
}

/**
 * Tests file handling with node revisions.
 */
class MediaFileFieldRevisionTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media file field revision test',
      'description' => 'Test creating and deleting revisions with files attached.',
      'group' => 'Media',
    );
  }

  /**
   * Tests creating multiple revisions of a node and managing attached files.
   *
   * Expected behaviors:
   *  - Adding a new revision will make another entry in the field table, but
   *    the original file will not be duplicated.
   *  - Deleting a revision should not delete the original file if the file
   *    is in use by another revision.
   *  - When the last revision that uses a file is deleted, the original file
   *    should be deleted also.
   */
  function testRevisions() {
    $type_name = 'article';
    $field_name = strtolower($this->randomName());
    $this->createFileField($field_name, $type_name);
    $field = field_info_field($field_name);
    $instance = field_info_instance('node', $field_name, $type_name);

    // Attach the same fields to users.
    $this->attachFileField($field_name, 'user', 'user');

    $test_file = $this->getTestFile('text');
    $test_file->uid = $this->admin_user->uid;
    $test_file = file_save($test_file);

    // Create a new node with the uploaded file.
    $nid = $this->attachNodeFile($test_file, $field_name, $type_name);

    // Check that the file exists on disk and in the database.
    $node = node_load($nid, NULL, TRUE);
    $node_file_r1 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $node_vid_r1 = $node->vid;
    $this->assertFileExists($node_file_r1, 'New file saved to disk on node creation.');
    $this->assertFileEntryExists($node_file_r1, 'File entry exists in database on node creation.');
    $this->assertFileIsPermanent($node_file_r1, 'File is permanent.');

    // Upload another file to the same node in a new revision.
    $this->replaceNodeFile($test_file, $field_name, $nid);
    $node = node_load($nid, NULL, TRUE);
    $node_file_r2 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $node_vid_r2 = $node->vid;
    $this->assertFileExists($node_file_r2, 'Replacement file exists on disk after creating new revision.');
    $this->assertFileEntryExists($node_file_r2, 'Replacement file entry exists in database after creating new revision.');
    $this->assertFileIsPermanent($node_file_r2, 'Replacement file is permanent.');

    // Check that the original file is still in place on the first revision.
    $node = node_load($nid, $node_vid_r1, TRUE);
    $this->assertEqual($node_file_r1, (object) $node->{$field_name}[LANGUAGE_NONE][0], 'Original file still in place after replacing file in new revision.');
    $this->assertFileExists($node_file_r1, 'Original file still in place after replacing file in new revision.');
    $this->assertFileEntryExists($node_file_r1, 'Original file entry still in place after replacing file in new revision');
    $this->assertFileIsPermanent($node_file_r1, 'Original file is still permanent.');

    // Save a new version of the node without any changes.
    // Check that the file is still the same as the previous revision.
    $this->drupalPost('node/' . $nid . '/edit', array('revision' => '1'), t('Save'));
    $node = node_load($nid, NULL, TRUE);
    $node_file_r3 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $node_vid_r3 = $node->vid;
    $this->assertEqual($node_file_r2, $node_file_r3, 'Previous revision file still in place after creating a new revision without a new file.');
    $this->assertFileIsPermanent($node_file_r3, 'New revision file is permanent.');

    // Revert to the first revision and check that the original file is active.
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r1 . '/revert', array(), t('Revert'));
    $node = node_load($nid, NULL, TRUE);
    $node_file_r4 = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $node_vid_r4 = $node->vid;
    $this->assertEqual($node_file_r1, $node_file_r4, 'Original revision file still in place after reverting to the original revision.');
    $this->assertFileIsPermanent($node_file_r4, 'Original revision file still permanent after reverting to the original revision.');

    // Delete the second revision and check that the file is kept (since it is
    // still being used by the third revision).
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r2 . '/delete', array(), t('Delete'));
    $this->assertFileExists($node_file_r3, 'Second file is still available after deleting second revision, since it is being used by the third revision.');
    $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting second revision, since it is being used by the third revision.');
    $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting second revision, since it is being used by the third revision.');

    // Attach the second file to a user.
    $user = $this->drupalCreateUser();
    $edit = (array) $user;
    $edit[$field_name][LANGUAGE_NONE][0] = (array) $node_file_r3;
    user_save($user, $edit);
    $this->drupalGet('user/' . $user->uid . '/edit');

    // Delete the third revision and check that the file is not deleted yet.
    $this->drupalPost('node/' . $nid . '/revisions/' . $node_vid_r3 . '/delete', array(), t('Delete'));
    $this->assertFileExists($node_file_r3, 'Second file is still available after deleting third revision, since it is being used by the user.');
    $this->assertFileEntryExists($node_file_r3, 'Second file entry is still available after deleting third revision, since it is being used by the user.');
    $this->assertFileIsPermanent($node_file_r3, 'Second file entry is still permanent after deleting third revision, since it is being used by the user.');

    // Delete the user and check that the file still exists.
    user_delete($user->uid);
    // TODO: This seems like a bug in File API. Clearing the stat cache should
    // not be necessary here. The file really exists, but stream wrappers
    // doesn't seem to think so unless we clear the PHP file stat() cache.
    clearstatcache();
    // @todo Files referenced from entity revisions cannot currently be deleted after the entity is deleted.
    // @see https://drupal.org/node/1613290
    // $this->assertFileNotExists($node_file_r3, 'Second file is now deleted after deleting third revision, since it is no longer being used by any other nodes.');
    // $this->assertFileEntryNotExists($node_file_r3, 'Second file entry is now deleted after deleting third revision, since it is no longer being used by any other nodes.');

    // Delete the entire node and check that the original file is deleted.
    $this->drupalPost('node/' . $nid . '/delete', array(), t('Delete'));
    $this->assertFileNotExists($node_file_r1, 'Original file is deleted after deleting the entire node with two revisions remaining.');
    $this->assertFileEntryNotExists($node_file_r1, 'Original file entry is deleted after deleting the entire node with two revisions remaining.');
  }
}

/**
 * Tests various validations.
 */
class MediaFileFieldValidateTestCase extends MediaFileFieldTestCase {
  protected $field;

  public static function getInfo() {
    return array(
      'name' => 'Media file field validation tests',
      'description' => 'Tests validation functions such as required.',
      'group' => 'Media',
    );
  }

  /**
   * Tests the required property on file fields.
   */
  function testRequired() {
    $type_name = 'article';
    $field_name = strtolower($this->randomName());
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
    $field = field_info_field($field_name);
    $instance = field_info_instance('node', $field_name, $type_name);

    $test_file = $this->getTestFile('text');
    $test_file->uid = $this->admin_user->uid;
    $test_file = file_save($test_file);

    // Try to post a new node without attaching a file.
    $langcode = LANGUAGE_NONE;
    $edit = array("title" => $this->randomName());
    $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
    $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required file field was empty.');

    // Create a new node with the attached file.
    $nid = $this->attachNodeFile($test_file, $field_name, $type_name);
    $this->assertTrue($nid !== FALSE, format_string('attachNodeFile(@test_file, @field_name, @type_name) succeeded', array('@test_file' => $test_file->uri, '@field_name' => $field_name, '@type_name' => $type_name)));

    $node = node_load($nid, NULL, TRUE);

    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $this->assertFileExists($node_file, 'File exists after attaching to the required field.');
    $this->assertFileEntryExists($node_file, 'File entry exists after attaching to the required field.');

    // Try again with a multiple value field.
    field_delete_field($field_name);
    $this->createFileField($field_name, $type_name, array('cardinality' => FIELD_CARDINALITY_UNLIMITED), array('required' => '1'));

    // Try to post a new node without attaching a file in the multivalue field.
    $edit = array('title' => $this->randomName());
    $this->drupalPost('node/add/' . $type_name, $edit, t('Save'));
    $this->assertRaw(t('!title field is required.', array('!title' => $instance['label'])), 'Node save failed when required multiple value file field was empty.');

    // Create a new node with the attached file into the multivalue field.
    $nid = $this->attachNodeFile($test_file, $field_name, $type_name);
    $node = node_load($nid, NULL, TRUE);
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $this->assertFileExists($node_file, 'File exists after attaching to the required multiple value field.');
    $this->assertFileEntryExists($node_file, 'File entry exists after attaching to the required multipel value field.');

    // Remove our file field.
    field_delete_field($field_name);
  }
}

/**
 * Tests that formatters are working properly.
 */
class MediaFileFieldDisplayTestCase extends MediaFileFieldTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Media file field display tests',
      'description' => 'Test the display of file fields in node and views.',
      'group' => 'Media',
    );
  }

  /**
   * Tests normal formatter display on node display.
   */
  function testNodeDisplay() {
    $field_name = strtolower($this->randomName());
    $type_name = 'article';
    $field_settings = array(
      'display_field' => '1',
      'display_default' => '1',
    );
    $instance_settings = array(
      'description_field' => '1',
    );
    $widget_settings = array();
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
    $field = field_info_field($field_name);
    $instance = field_info_instance('node', $field_name, $type_name);

    // Create a new node *without* the file field set, and check that the field
    // is not shown for each node display.
    $node = $this->drupalCreateNode(array('type' => $type_name));
    $file_formatters = array('file_default', 'file_table', 'file_url_plain', 'hidden');
    foreach ($file_formatters as $formatter) {
      $edit = array(
        "fields[$field_name][type]" => $formatter,
      );
      $this->drupalPost("admin/structure/types/manage/$type_name/display", $edit, t('Save'));
      $this->drupalGet('node/' . $node->nid);
      $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
    }

    $test_file = $this->getTestFile('text');
    $test_file->uid = $this->admin_user->uid;
    $test_file = file_save($test_file);

    // Create a new node with the attached file.
    $nid = $this->attachNodeFile($test_file, $field_name, $type_name);
    $this->drupalGet('node/' . $nid . '/edit');

    // Check that the media thumbnail is displaying with the file name.
    $node = node_load($nid, NULL, TRUE);
    $node_file = (object) $node->{$field_name}[LANGUAGE_NONE][0];
    $thumbnail = media_get_thumbnail_preview($node_file);
    $default_output = drupal_render($thumbnail);
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');

    // Turn the "display" option off and check that the file is no longer displayed.
    $edit = array($field_name . '[' . LANGUAGE_NONE . '][0][display]' => FALSE);
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));

    $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');

  }
}