Projet

Général

Profil

Révision ca0757b9

Ajouté par Assos Assos il y a plus de 9 ans

Weekly update of contrib modules

Voir les différences:

drupal7/sites/all/modules/media/tests/media.test
6 6
 */
7 7

  
8 8
/**
9
 * Defines base class for media test cases.
9
 * Provides methods specifically for testing Media module's field handling.
10 10
 */
11
class MediaTestHelper extends DrupalWebTestCase {
11
class MediaFileFieldTestCase extends DrupalWebTestCase {
12
  protected $admin_user;
13

  
14
  function setUp() {
15
    // Since this is a base class for many test cases, support the same
16
    // flexibility that DrupalWebTestCase::setUp() has for the modules to be
17
    // passed in as either an array or a variable number of string arguments.
18
    $modules = func_get_args();
19
    if (isset($modules[0]) && is_array($modules[0])) {
20
      $modules = $modules[0];
21
    }
22
    $modules[] = 'media';
23
    $modules[] = 'media_module_test';
24
    parent::setUp($modules);
25
    $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'));
26
    $this->drupalLogin($this->admin_user);
27
  }
28

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

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

  
39
    return $file;
40
  }
41

  
42
  /**
43
   * Creates a new file entity.
44
   *
45
   * @param $settings
46
   *   A list of settings that will be added to the entity defaults.
47
   */
48
  protected function createFileEntity($settings = array()) {
49
    $file = new stdClass();
50

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

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

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

  
68
    $file = new stdClass();
69
    $file->uri = $filepath;
70
    $file->filename = drupal_basename($file->uri);
71
    $file->filemime = $settings['filemime'];
72
    $file->uid = $settings['uid'];
73
    $file->timestamp = $settings['timestamp'];
74
    $file->filesize = filesize($file->uri);
75
    $file->status = $settings['status'];
76
    $file->type = $settings['type'];
77

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

  
83
    // If the file isn't already assigned a real type, determine what type should
84
    // be assigned to it.
85
    if ($file->type === FILE_TYPE_NONE) {
86
      $type = file_get_type($file);
87
      if (isset($type)) {
88
        $file->type = $type;
89
      }
90
    }
91

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

  
96
    return $file;
97
  }
98

  
99
  /**
100
   * Creates a new file field.
101
   *
102
   * @param $name
103
   *   The name of the new field (all lowercase), exclude the "field_" prefix.
104
   * @param $type_name
105
   *   The node type that this field will be added to.
106
   * @param $field_settings
107
   *   A list of field settings that will be added to the defaults.
108
   * @param $instance_settings
109
   *   A list of instance settings that will be added to the instance defaults.
110
   * @param $widget_settings
111
   *   A list of widget settings that will be added to the widget defaults.
112
   */
113
  function createFileField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
114
    $field = array(
115
      'field_name' => $name,
116
      'type' => 'file',
117
      'settings' => array(),
118
      'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
119
    );
120
    $field['settings'] = array_merge($field['settings'], $field_settings);
121
    field_create_field($field);
122

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

  
126
  /**
127
   * Attaches a file field to an entity.
128
   *
129
   * @param $name
130
   *   The name of the new field (all lowercase), exclude the "field_" prefix.
131
   * @param $entity_type
132
   *   The entity type this field will be added to.
133
   * @param $bundle
134
   *   The bundle this field will be added to.
135
   * @param $field_settings
136
   *   A list of field settings that will be added to the defaults.
137
   * @param $instance_settings
138
   *   A list of instance settings that will be added to the instance defaults.
139
   * @param $widget_settings
140
   *   A list of widget settings that will be added to the widget defaults.
141
   */
142
  function attachFileField($name, $entity_type, $bundle, $instance_settings = array(), $widget_settings = array()) {
143
    $instance = array(
144
      'field_name' => $name,
145
      'label' => $name,
146
      'entity_type' => $entity_type,
147
      'bundle' => $bundle,
148
      'required' => !empty($instance_settings['required']),
149
      'settings' => array(),
150
      'widget' => array(
151
        'type' => 'media_generic',
152
        'settings' => array(),
153
      ),
154
    );
155
    $instance['settings'] = array_merge($instance['settings'], $instance_settings);
156
    $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
157
    field_create_instance($instance);
158
  }
159

  
160
  /**
161
   * Attaches a file to a node.
162
   */
163
  function attachNodeFile($file, $field_name, $nid_or_type, $new_revision = TRUE, $extras = array()) {
164
    $langcode = LANGUAGE_NONE;
165
    $edit = array(
166
      "title" => $this->randomName(),
167
      'revision' => (string) (int) $new_revision,
168
    );
169

  
170
    if (is_numeric($nid_or_type)) {
171
      $nid = $nid_or_type;
172
    }
173
    else {
174
      // Add a new node.
175
      $extras['type'] = $nid_or_type;
176
      $node = $this->drupalCreateNode($extras);
177
      $nid = $node->nid;
178
      // Save at least one revision to better simulate a real site.
179
      $this->drupalCreateNode(get_object_vars($node));
180
      $node = node_load($nid, NULL, TRUE);
181
      $this->assertNotEqual($nid, $node->vid, 'Node revision exists.');
182
    }
183

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

  
188
    return $nid;
189
  }
190

  
191
  /**
192
   * Replaces a file within a node.
193
   */
194
  function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
195
    $edit = array(
196
      $field_name . '[' . LANGUAGE_NONE . '][0][fid]' => $file->fid,
197
      'revision' => (string) (int) $new_revision,
198
    );
199

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

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

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

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

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

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

  
248
/**
249
 * Tests the 'media' element type.
250
 *
251
 * @todo Create a MediaFileTestCase base class and move MediaFileFieldTestCase
252
 *   methods that aren't related to fields into it.
253
 */
254
class MediaElementTestCase extends MediaFileFieldTestCase {
255
  public static function getInfo() {
256
    return array(
257
      'name' => 'Media element test',
258
      'description' => 'Tests the media element type.',
259
      'group' => 'Media',
260
    );
261
  }
262

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

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

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

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

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

  
304
          // Attach, then Remove, then Submit.
305
          $this->drupalGet($path);
306
          $edit = array('media[' . $input_base_name . ']' => $test_file->fid);
307
          if ($ajax) {
308
            $this->drupalPostAJAX(NULL, $edit, $input_base_name . '_attach_button');
309
            $this->drupalPostAJAX(NULL, array(), $input_base_name . '_remove_button');
310
          }
311
          else {
312
            $this->drupalPost(NULL, $edit, t('Attach'));
313
            $this->drupalPost(NULL, array(), t('Remove'));
314
          }
315
          $this->drupalPost(NULL, array(), t('Save'));
316
          $this->assertRaw(t('The file id is %fid.', array('%fid' => 0)), 'Submission after file attachment and removal was successful.');
317
        }
318
      }
319
    }
320
  }
321
}
322

  
323
/**
324
 * Test media file administration page functionality.
325
 */
326
class MediaAdminTestCase extends MediaFileFieldTestCase {
327
  public static function getInfo() {
328
    return array(
329
      'name' => 'Media file administration',
330
      'description' => 'Test media file administration page functionality.',
331
      'group' => 'Media',
332
    );
333
  }
334

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

  
345
    $this->base_user_1 = $this->drupalCreateUser(array('administer files'));
346
    $this->base_user_2 = $this->drupalCreateUser(array('administer files', 'view own private files'));
347
    $this->base_user_3 = $this->drupalCreateUser(array('administer files', 'view private files'));
348
    $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'));
349
  }
350

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

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

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

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

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

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

  
400
    // Verify view and edit links for any file.
401
    $this->drupalGet('admin/content/file/thumbnails');
402
    $this->assertResponse(200);
403
    foreach ($files as $file) {
404
      $this->assertLinkByHref('file/' . $file->fid);
405
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
406
      // Verify tableselect.
407
      $this->assertFieldByName('files[' . $file->fid . ']', '', t('Tableselect found.'));
408
    }
409

  
410
    // Verify no operation links are displayed for regular users.
411
    $this->drupalLogout();
412
    $this->drupalLogin($this->base_user_1);
413
    $this->drupalGet('admin/content/file/thumbnails');
414
    $this->assertResponse(200);
415
    $this->assertLinkByHref('file/' . $files['public_image']->fid);
416
    $this->assertLinkByHref('file/' . $files['public_document']->fid);
417
    $this->assertNoLinkByHref('file/' . $files['public_image']->fid . '/edit');
418
    $this->assertNoLinkByHref('file/' . $files['public_document']->fid . '/edit');
419

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

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

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

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

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

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

  
449
    // Verify operation links are displayed for users with appropriate permission.
450
    $this->drupalLogout();
451
    $this->drupalLogin($this->base_user_4);
452
    $this->drupalGet('admin/content/file/thumbnails');
453
    $this->assertResponse(200);
454
    foreach ($files as $file) {
455
      $this->assertLinkByHref('file/' . $file->fid);
456
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
457
    }
458

  
459
    // Verify file access can be bypassed.
460
    $this->drupalLogout();
461
    $this->drupalLogin($this->admin_user);
462
    $this->drupalGet('admin/content/file/thumbnails');
463
    $this->assertResponse(200);
464
    foreach ($files as $file) {
465
      $this->assertLinkByHref('file/' . $file->fid);
466
      $this->assertLinkByHref('file/' . $file->fid . '/edit');
467
    }
468
  }
469
}
470

  
471
/**
472
 * Tests the media browser 'Library' tab.
473
 */
474
class MediaBrowserLibraryTestCase extends MediaFileFieldTestCase {
475
  public static function getInfo() {
476
    return array(
477
      'name' => 'Media browser library test',
478
      'description' => 'Tests the media browser library tab.',
479
      'group' => 'Media',
480
    );
481
  }
482

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

  
490
  /**
491
   * Tests that the views sorting works on the media browser 'Library' tab.
492
   */
493
  function testFilesBrowserSort() {
494
    // Load only the 'Library' tab of the media browser.
495
    $options = array(
496
      'query' => array(
497
        'enabledPlugins' => array(
498
          'media_default--media_browser_1' => 'media_default--media_browser_1',
499
        ),
500
      ),
501
    );
502

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

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

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

  
13 524
  /**
14
   * Enable media and file entity modules for testing.
525
   * Tests media browser 'Library' tab with different user permissions.
15 526
   */
16
  public function setUp() {
17
    parent::setUp(array('media', 'file_entity'));
527
  function testFilesBrowserLibrary() {
528
    // Load only the 'Library' tab of the media browser.
529
    $options = array(
530
      'query' => array(
531
        'enabledPlugins' => array(
532
          'media_default--media_browser_1' => 'media_default--media_browser_1',
533
        ),
534
      ),
535
    );
536

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

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

  
552
    // Verify public files are displayed.
553
    $this->drupalLogout();
554
    $this->drupalLogin($this->base_user_1);
555
    $this->drupalGet('media/browser', $options);
556
    $this->assertResponse(200);
557
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
558
      ':fid' => $files['public_image']->fid,
559
    ));
560
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['public_image']->fid)));
561
    $xpath = $this->buildXPathQuery('//ul[@class="media-list-thumbnails"]/li/div[@data-fid=:fid]/@data-fid', array(
562
      ':fid' => $files['public_document']->fid,
563
    ));
564
    $this->assertFieldByXPath($xpath, TRUE, format_string('File with file ID %fid found.', array('%fid' => $files['public_document']->fid)));
565

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

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

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

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

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

  
612
/**
613
 * Tests the media browser settings.
614
 */
615
class MediaBrowserSettingsTestCase extends MediaFileFieldTestCase {
616
  public static function getInfo() {
617
    return array(
618
      'name' => 'Media browser settings test',
619
      'description' => 'Tests the media browser settings.',
620
      'group' => 'Media',
621
    );
622
  }
623

  
624
  function setUp() {
625
    parent::setUp('file_test');
626
  }
627

  
628
  /**
629
   * Tests the media browser settings.
630
   */
631
  function testBrowserSettings() {
632
    $settings = array(
633
      'scheme' => array('public', 'private'),
634
      'type' => array('image', 'document'),
635
      'extension' => array('jpg', 'txt'),
636
    );
637

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

  
645
          $options = array(
646
            'query' => array(
647
              'enabledPlugins' => array(
648
                'media_default--media_browser_1' => 'media_default--media_browser_1',
649
              ),
650
              'schemes' => array($scheme),
651
              'types' => array($type),
652
              'file_extensions' => $extension,
653
            ),
654
          );
655

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

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

  
671
    // Perform the tests with none and all of the restrictions.
672
    foreach (array('none', 'all') as $restrictions) {
673
      $options = array(
674
        'query' => array(
675
          'enabledPlugins' => array(
676
            'media_default--media_browser_1' => 'media_default--media_browser_1',
677
          ),
678
        ),
679
      );
680

  
681
      switch ($restrictions) {
682
        case 'none':
683
          $options['query']['schemes'] = array();
684
          $options['query']['types'] = array();
685
          $options['query']['file_extensions'] = array();
686
          break;
687
        case 'all':
688
          $options['query']['schemes'] = $settings['scheme'];
689
          $options['query']['types'] = $settings['type'];
690
          $options['query']['file_extensions'] = implode(' ', $settings['extension']);
691
          break;
692
      }
693

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

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

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

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

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

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

  
733
/**
734
 * Tests the media browser 'My files' tab.
735
 */
736
class MediaBrowserMyFilesTestCase extends MediaFileFieldTestCase {
737
  public static function getInfo() {
738
    return array(
739
      'name' => 'Media browser my files test',
740
      'description' => 'Tests the media browser my files tab.',
741
      'group' => 'Media',
742
    );
743
  }
744

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

  
752
  /**
753
   * Tests media browser 'My files' tab with different user permissions.
754
   */
755
  function testFilesBrowserMyFiles() {
756
    // Load only the 'My files' tab of the media browser.
757
    $options = array(
758
      'query' => array(
759
        'enabledPlugins' => array(
760
          'media_default--media_browser_my_files' => 'media_default--media_browser_my_files',
761
        ),
762
      ),
763
    );
764

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

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

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

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

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

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

  
821
/**
822
 * Tests the 'media' element type settings.
823
 */
824
class MediaElementSettingsTestCase extends MediaFileFieldTestCase {
825
  public static function getInfo() {
826
    return array(
827
      'name' => 'Media element settings test',
828
      'description' => 'Tests the media element type JavaScript settings.',
829
      'group' => 'Media',
830
    );
831
  }
832

  
833
  /**
834
   * Tests the media element type settings.
835
   */
836
  function testElementSettings() {
837
    $form = array(
838
      '#type' => 'media',
839
    );
840
    drupal_render($form);
841
    $javascript = drupal_get_js();
842
    $global = array(
843
      'media' => array(
844
        'global' => array(
845
          'global' => array(
846
            'types' => array(),
847
            'schemes' => array(),
848
          ),
849
        ),
850
      ),
851
    );
852
    $settings = drupal_json_encode(drupal_array_merge_deep_array($global));
853
    $this->assertTrue(strpos($javascript, $settings) > 0, 'Rendered media element adds the global settings.');
854
  }
855

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

  
870
    $javascript = $this->drupalGet("node/add/$type_name");
871
    $field_widget = array(
872
        'elements' => array(
873
          '#edit-' . $field_name . '-' . LANGUAGE_NONE . '-0' => array(
874
            'global' => array(
875
              'types' => array(
876
                0 => 'image',
877
              ),
878
              'enabledPlugins' => array(),
879
              'schemes' => array(
880
                0 => 'public',
881
                1 => 'private',
882
              ),
883
              'file_directory' => '',
884
              'file_extensions' => 'txt',
885
              'max_filesize' => '',
886
              'uri_scheme' => 'public',
887
            ),
888
          ),
889
        ),
890
    );
891
    $settings = drupal_json_encode(drupal_array_merge_deep_array($field_widget));
892
    $this->assertTrue(strpos($javascript, $settings) > 0, 'Media file field widget adds element-specific settings.');
893
  }
894
}
895

  
896
/**
897
 * Tests file handling with node revisions.
898
 */
899
class MediaFileFieldRevisionTestCase extends MediaFileFieldTestCase {
900
  public static function getInfo() {
901
    return array(
902
      'name' => 'Media file field revision test',
903
      'description' => 'Test creating and deleting revisions with files attached.',
904
      'group' => 'Media',
905
    );
906
  }
907

  
908
  /**
909
   * Tests creating multiple revisions of a node and managing attached files.
910
   *
911
   * Expected behaviors:
912
   *  - Adding a new revision will make another entry in the field table, but
913
   *    the original file will not be duplicated.
914
   *  - Deleting a revision should not delete the original file if the file
915
   *    is in use by another revision.
916
   *  - When the last revision that uses a file is deleted, the original file
917
   *    should be deleted also.
918
   */
919
  function testRevisions() {
920
    $type_name = 'article';
921
    $field_name = strtolower($this->randomName());
922
    $this->createFileField($field_name, $type_name);
923
    $field = field_info_field($field_name);
924
    $instance = field_info_instance('node', $field_name, $type_name);
925

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

  
929
    $test_file = $this->getTestFile('text');
930
    $test_file->uid = $this->admin_user->uid;
931
    $test_file = file_save($test_file);
932

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

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

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

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

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

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

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

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

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

  
997
    // Delete the user and check that the file still exists.
998
    user_delete($user->uid);
999
    // TODO: This seems like a bug in File API. Clearing the stat cache should
1000
    // not be necessary here. The file really exists, but stream wrappers
1001
    // doesn't seem to think so unless we clear the PHP file stat() cache.
1002
    clearstatcache();
1003
    // @todo Files referenced from entity revisions cannot currently be deleted after the entity is deleted.
1004
    // @see https://drupal.org/node/1613290
1005
    // $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.');
1006
    // $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.');
1007

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

  
1015
/**
1016
 * Tests various validations.
1017
 */
1018
class MediaFileFieldValidateTestCase extends MediaFileFieldTestCase {
1019
  protected $field;
1020

  
1021
  public static function getInfo() {
1022
    return array(
1023
      'name' => 'Media file field validation tests',
1024
      'description' => 'Tests validation functions such as required.',
1025
      'group' => 'Media',
1026
    );
1027
  }
1028

  
1029
  /**
1030
   * Tests the required property on file fields.
1031
   */
1032
  function testRequired() {
1033
    $type_name = 'article';
1034
    $field_name = strtolower($this->randomName());
1035
    $this->createFileField($field_name, $type_name, array(), array('required' => '1'));
1036
    $field = field_info_field($field_name);
1037
    $instance = field_info_instance('node', $field_name, $type_name);
1038

  
1039
    $test_file = $this->getTestFile('text');
1040
    $test_file->uid = $this->admin_user->uid;
1041
    $test_file = file_save($test_file);
1042

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

  
1049
    // Create a new node with the attached file.
1050
    $nid = $this->attachNodeFile($test_file, $field_name, $type_name);
1051
    $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)));
1052

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

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

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

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

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

  
1075
    // Remove our file field.
1076
    field_delete_field($field_name);
1077
  }
1078
}
1079

  
1080
/**
1081
 * Tests that formatters are working properly.
1082
 */
1083
class MediaFileFieldDisplayTestCase extends MediaFileFieldTestCase {
1084
  public static function getInfo() {
1085
    return array(
1086
      'name' => 'Media file field display tests',
1087
      'description' => 'Test the display of file fields in node and views.',
1088
      'group' => 'Media',
1089
    );
1090
  }
1091

  
1092
  /**
1093
   * Tests normal formatter display on node display.
1094
   */
1095
  function testNodeDisplay() {
1096
    $field_name = strtolower($this->randomName());
1097
    $type_name = 'article';
1098
    $field_settings = array(
1099
      'display_field' => '1',
1100
      'display_default' => '1',
1101
    );
1102
    $instance_settings = array(
1103
      'description_field' => '1',
1104
    );
1105
    $widget_settings = array();
1106
    $this->createFileField($field_name, $type_name, $field_settings, $instance_settings, $widget_settings);
1107
    $field = field_info_field($field_name);
1108
    $instance = field_info_instance('node', $field_name, $type_name);
1109

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

  
1123
    $test_file = $this->getTestFile('text');
1124
    $test_file->uid = $this->admin_user->uid;
1125
    $test_file = file_save($test_file);
1126

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

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

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

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

  
18 1144
  }
19 1145
}

Formats disponibles : Unified diff