Projet

Général

Profil

Paste
Télécharger (76,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / image / image.test @ b4adf10d

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for image.module.
6
 */
7

    
8
/**
9
 * TODO: Test the following functions.
10
 *
11
 * image.effects.inc:
12
 *   image_style_generate()
13
 *   image_style_create_derivative()
14
 *
15
 * image.module:
16
 *   image_style_load()
17
 *   image_style_save()
18
 *   image_style_delete()
19
 *   image_style_options()
20
 *   image_effect_definition_load()
21
 *   image_effect_load()
22
 *   image_effect_save()
23
 *   image_effect_delete()
24
 *   image_filter_keyword()
25
 */
26

    
27
/**
28
 * This class provides methods specifically for testing Image's field handling.
29
 */
30
class ImageFieldTestCase extends DrupalWebTestCase {
31
  protected $admin_user;
32

    
33
  function setUp() {
34
    parent::setUp('image');
35
    $this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer content types', 'administer nodes', 'create article content', 'edit any article content', 'delete any article content', 'administer image styles'));
36
    $this->drupalLogin($this->admin_user);
37
  }
38

    
39
  /**
40
   * Create a new image field.
41
   *
42
   * @param $name
43
   *   The name of the new field (all lowercase), exclude the "field_" prefix.
44
   * @param $type_name
45
   *   The node type that this field will be added to.
46
   * @param $field_settings
47
   *   A list of field settings that will be added to the defaults.
48
   * @param $instance_settings
49
   *   A list of instance settings that will be added to the instance defaults.
50
   * @param $widget_settings
51
   *   A list of widget settings that will be added to the widget defaults.
52
   */
53
  function createImageField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
54
    $field = array(
55
      'field_name' => $name,
56
      'type' => 'image',
57
      'settings' => array(),
58
      'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
59
    );
60
    $field['settings'] = array_merge($field['settings'], $field_settings);
61
    field_create_field($field);
62

    
63
    $instance = array(
64
      'field_name' => $field['field_name'],
65
      'entity_type' => 'node',
66
      'label' => $name,
67
      'bundle' => $type_name,
68
      'required' => !empty($instance_settings['required']),
69
      'settings' => array(),
70
      'widget' => array(
71
        'type' => 'image_image',
72
        'settings' => array(),
73
      ),
74
    );
75
    $instance['settings'] = array_merge($instance['settings'], $instance_settings);
76
    $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
77
    return field_create_instance($instance);
78
  }
79

    
80
  /**
81
   * Upload an image to a node.
82
   *
83
   * @param $image
84
   *   A file object representing the image to upload.
85
   * @param $field_name
86
   *   Name of the image field the image should be attached to.
87
   * @param $type
88
   *   The type of node to create.
89
   */
90
  function uploadNodeImage($image, $field_name, $type) {
91
    $edit = array(
92
      'title' => $this->randomName(),
93
    );
94
    $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = drupal_realpath($image->uri);
95
    $this->drupalPost('node/add/' . $type, $edit, t('Save'));
96

    
97
    // Retrieve ID of the newly created node from the current URL.
98
    $matches = array();
99
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
100
    return isset($matches[1]) ? $matches[1] : FALSE;
101
  }
102
}
103

    
104
/**
105
 * Tests the functions for generating paths and URLs for image styles.
106
 */
107
class ImageStylesPathAndUrlTestCase extends DrupalWebTestCase {
108
  protected $style_name;
109
  protected $image_info;
110
  protected $image_filepath;
111

    
112
  public static function getInfo() {
113
    return array(
114
      'name' => 'Image styles path and URL functions',
115
      'description' => 'Tests functions for generating paths and URLs to image styles.',
116
      'group' => 'Image',
117
    );
118
  }
119

    
120
  function setUp() {
121
    parent::setUp('image_module_test');
122

    
123
    $this->style_name = 'style_foo';
124
    image_style_save(array('name' => $this->style_name, 'label' => $this->randomString()));
125
  }
126

    
127
  /**
128
   * Test image_style_path().
129
   */
130
  function testImageStylePath() {
131
    $scheme = 'public';
132
    $actual = image_style_path($this->style_name, "$scheme://foo/bar.gif");
133
    $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
134
    $this->assertEqual($actual, $expected, 'Got the path for a file URI.');
135

    
136
    $actual = image_style_path($this->style_name, 'foo/bar.gif');
137
    $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
138
    $this->assertEqual($actual, $expected, 'Got the path for a relative file path.');
139
  }
140

    
141
  /**
142
   * Test image_style_url() with a file using the "public://" scheme.
143
   */
144
  function testImageStyleUrlAndPathPublic() {
145
    $this->_testImageStyleUrlAndPath('public');
146
  }
147

    
148
  /**
149
   * Test image_style_url() with a file using the "private://" scheme.
150
   */
151
  function testImageStyleUrlAndPathPrivate() {
152
    $this->_testImageStyleUrlAndPath('private');
153
  }
154

    
155
  /**
156
   * Test image_style_url() with the "public://" scheme and unclean URLs.
157
   */
158
   function testImageStylUrlAndPathPublicUnclean() {
159
     $this->_testImageStyleUrlAndPath('public', FALSE);
160
   }
161

    
162
  /**
163
   * Test image_style_url() with the "private://" schema and unclean URLs.
164
   */
165
  function testImageStyleUrlAndPathPrivateUnclean() {
166
    $this->_testImageStyleUrlAndPath('private', FALSE);
167
  }
168

    
169
  /**
170
   * Test image_style_url() with a file URL that has an extra slash in it.
171
   */
172
  function testImageStyleUrlExtraSlash() {
173
    $this->_testImageStyleUrlAndPath('public', TRUE, TRUE);
174
  }
175

    
176
  /**
177
   * Test that an invalid source image returns a 404.
178
   */
179
  function testImageStyleUrlForMissingSourceImage() {
180
    $non_existent_uri = 'public://foo.png';
181
    $generated_url = image_style_url($this->style_name, $non_existent_uri);
182
    $this->drupalGet($generated_url);
183
    $this->assertResponse(404, 'Accessing an image style URL with a source image that does not exist provides a 404 error response.');
184
  }
185

    
186
  /**
187
   * Test image_style_url().
188
   */
189
  function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FALSE) {
190
    // Make the default scheme neither "public" nor "private" to verify the
191
    // functions work for other than the default scheme.
192
    variable_set('file_default_scheme', 'temporary');
193
    variable_set('clean_url', $clean_url);
194

    
195
    // Create the directories for the styles.
196
    $directory = $scheme . '://styles/' . $this->style_name;
197
    $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
198
    $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
199

    
200
    // Create a working copy of the file.
201
    $files = $this->drupalGetTestFiles('image');
202
    $file = array_shift($files);
203
    $image_info = image_get_info($file->uri);
204
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
205
    // Let the image_module_test module know about this file, so it can claim
206
    // ownership in hook_file_download().
207
    variable_set('image_module_test_file_download', $original_uri);
208
    $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
209

    
210
    // Get the URL of a file that has not been generated and try to create it.
211
    $generated_uri = image_style_path($this->style_name, $original_uri);
212
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
213
    $generate_url = image_style_url($this->style_name, $original_uri);
214

    
215
    // Ensure that the tests still pass when the file is generated by accessing
216
    // a poorly constructed (but still valid) file URL that has an extra slash
217
    // in it.
218
    if ($extra_slash) {
219
      $modified_uri = str_replace('://', ':///', $original_uri);
220
      $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
221
      $generate_url = image_style_url($this->style_name, $modified_uri);
222
    }
223

    
224
    if (!$clean_url) {
225
      $this->assertTrue(strpos($generate_url, '?q=') !== FALSE, 'When using non-clean URLS, the system path contains the query string.');
226
    }
227
    // Add some extra chars to the token.
228
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
229
    $this->assertResponse(403, 'Image was inaccessible at the URL with an invalid token.');
230
    // Change the parameter name so the token is missing.
231
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
232
    $this->assertResponse(403, 'Image was inaccessible at the URL with a missing token.');
233

    
234
    // Check that the generated URL is the same when we pass in a relative path
235
    // rather than a URI. We need to temporarily switch the default scheme to
236
    // match the desired scheme before testing this, then switch it back to the
237
    // "temporary" scheme used throughout this test afterwards.
238
    variable_set('file_default_scheme', $scheme);
239
    $relative_path = file_uri_target($original_uri);
240
    $generate_url_from_relative_path = image_style_url($this->style_name, $relative_path);
241
    $this->assertEqual($generate_url, $generate_url_from_relative_path, 'Generated URL is the same regardless of whether it came from a relative path or a file URI.');
242
    variable_set('file_default_scheme', 'temporary');
243

    
244
    // Fetch the URL that generates the file.
245
    $this->drupalGet($generate_url);
246
    $this->assertResponse(200, 'Image was generated at the URL.');
247
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
248
    $this->assertRaw(file_get_contents($generated_uri), 'URL returns expected file.');
249
    $generated_image_info = image_get_info($generated_uri);
250
    $this->assertEqual($this->drupalGetHeader('Content-Type'), $generated_image_info['mime_type'], 'Expected Content-Type was reported.');
251
    $this->assertEqual($this->drupalGetHeader('Content-Length'), $generated_image_info['file_size'], 'Expected Content-Length was reported.');
252
    if ($scheme == 'private') {
253
      $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
254
      $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate, post-check=0, pre-check=0', 'Cache-Control header was set to prevent caching.');
255
      $this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
256

    
257
      // Make sure that a second request to the already existing derivate works
258
      // too.
259
      $this->drupalGet($generate_url);
260
      $this->assertResponse(200, 'Image was generated at the URL.');
261

    
262
      // Make sure that access is denied for existing style files if we do not
263
      // have access.
264
      variable_del('image_module_test_file_download');
265
      $this->drupalGet($generate_url);
266
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
267

    
268
      // Repeat this with a different file that we do not have access to and
269
      // make sure that access is denied.
270
      $file_noaccess = array_shift($files);
271
      $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
272
      $generated_uri_noaccess = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/'. drupal_basename($original_uri_noaccess);
273
      $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
274
      $generate_url_noaccess = image_style_url($this->style_name, $original_uri_noaccess);
275

    
276
      $this->drupalGet($generate_url_noaccess);
277
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
278
      // Verify that images are not appended to the response. Currently this test only uses PNG images.
279
      if (strpos($generate_url, '.png') === FALSE ) {
280
        $this->fail('Confirming that private image styles are not appended require PNG file.');
281
      }
282
      else {
283
        // Check for PNG-Signature (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2) in the
284
        // response body.
285
        $this->assertNoRaw( chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10), 'No PNG signature found in the response body.');
286
      }
287
    }
288
    elseif ($clean_url) {
289
      // Add some extra chars to the token.
290
      $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
291
      $this->assertResponse(200, 'Existing image was accessible at the URL with an invalid token.');
292
    }
293

    
294
    // Allow insecure image derivatives to be created for the remainder of this
295
    // test.
296
    variable_set('image_allow_insecure_derivatives', TRUE);
297

    
298
    // Create another working copy of the file.
299
    $files = $this->drupalGetTestFiles('image');
300
    $file = array_shift($files);
301
    $image_info = image_get_info($file->uri);
302
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
303
    // Let the image_module_test module know about this file, so it can claim
304
    // ownership in hook_file_download().
305
    variable_set('image_module_test_file_download', $original_uri);
306

    
307
    // Get the URL of a file that has not been generated and try to create it.
308
    $generated_uri = image_style_path($this->style_name, $original_uri);
309
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
310
    $generate_url = image_style_url($this->style_name, $original_uri);
311

    
312
    // Check that the image is accessible even without the security token.
313
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
314
    $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
315

    
316
    // Check that a security token is still required when generating a second
317
    // image derivative using the first one as a source.
318
    $nested_uri = image_style_path($this->style_name, $generated_uri);
319
    $nested_url = image_style_url($this->style_name, $generated_uri);
320
    $nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $nested_url);
321
    $this->drupalGet($nested_url_with_wrong_token);
322
    $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token.');
323
    // Check that this restriction cannot be bypassed by adding extra slashes
324
    // to the URL.
325
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
326
    $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token, even with an extra forward slash in the URL.');
327
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '/\styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
328
    $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token, even with an extra backslash in the URL.');
329
    // Make sure the image can still be generated if a correct token is used.
330
    $this->drupalGet($nested_url);
331
    $this->assertResponse(200, 'Image was accessible when a correct token was provided in the URL.');
332

    
333
    // Check that requesting a nonexistent image does not create any new
334
    // directories in the file system.
335
    $directory = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/' . $this->randomName();
336
    $this->drupalGet(file_create_url($directory . '/' . $this->randomName()));
337
    $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
338
  }
339
}
340

    
341
/**
342
 * Use the image_test.module's mock toolkit to ensure that the effects are
343
 * properly passing parameters to the image toolkit.
344
 */
345
class ImageEffectsUnitTest extends ImageToolkitTestCase {
346
  public static function getInfo() {
347
    return array(
348
      'name' => 'Image effects',
349
      'description' => 'Test that the image effects pass parameters to the toolkit correctly.',
350
      'group' => 'Image',
351
    );
352
  }
353

    
354
  function setUp() {
355
    parent::setUp('image_module_test');
356
    module_load_include('inc', 'image', 'image.effects');
357
  }
358

    
359
  /**
360
   * Test the image_resize_effect() function.
361
   */
362
  function testResizeEffect() {
363
    $this->assertTrue(image_resize_effect($this->image, array('width' => 1, 'height' => 2)), 'Function returned the expected value.');
364
    $this->assertToolkitOperationsCalled(array('resize'));
365

    
366
    // Check the parameters.
367
    $calls = image_test_get_all_calls();
368
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
369
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
370
  }
371

    
372
  /**
373
   * Test the image_scale_effect() function.
374
   */
375
  function testScaleEffect() {
376
    // @todo: need to test upscaling.
377
    $this->assertTrue(image_scale_effect($this->image, array('width' => 10, 'height' => 10)), 'Function returned the expected value.');
378
    $this->assertToolkitOperationsCalled(array('resize'));
379

    
380
    // Check the parameters.
381
    $calls = image_test_get_all_calls();
382
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
383
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
384
  }
385

    
386
  /**
387
   * Test the image_crop_effect() function.
388
   */
389
  function testCropEffect() {
390
    // @todo should test the keyword offsets.
391
    $this->assertTrue(image_crop_effect($this->image, array('anchor' => 'top-1', 'width' => 3, 'height' => 4)), 'Function returned the expected value.');
392
    $this->assertToolkitOperationsCalled(array('crop'));
393

    
394
    // Check the parameters.
395
    $calls = image_test_get_all_calls();
396
    $this->assertEqual($calls['crop'][0][1], 0, 'X was passed correctly');
397
    $this->assertEqual($calls['crop'][0][2], 1, 'Y was passed correctly');
398
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
399
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
400
  }
401

    
402
  /**
403
   * Test the image_scale_and_crop_effect() function.
404
   */
405
  function testScaleAndCropEffect() {
406
    $this->assertTrue(image_scale_and_crop_effect($this->image, array('width' => 5, 'height' => 10)), 'Function returned the expected value.');
407
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));
408

    
409
    // Check the parameters.
410
    $calls = image_test_get_all_calls();
411
    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
412
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
413
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
414
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
415
  }
416

    
417
  /**
418
   * Test the image_desaturate_effect() function.
419
   */
420
  function testDesaturateEffect() {
421
    $this->assertTrue(image_desaturate_effect($this->image, array()), 'Function returned the expected value.');
422
    $this->assertToolkitOperationsCalled(array('desaturate'));
423

    
424
    // Check the parameters.
425
    $calls = image_test_get_all_calls();
426
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
427
  }
428

    
429
  /**
430
   * Test the image_rotate_effect() function.
431
   */
432
  function testRotateEffect() {
433
    // @todo: need to test with 'random' => TRUE
434
    $this->assertTrue(image_rotate_effect($this->image, array('degrees' => 90, 'bgcolor' => '#fff')), 'Function returned the expected value.');
435
    $this->assertToolkitOperationsCalled(array('rotate'));
436

    
437
    // Check the parameters.
438
    $calls = image_test_get_all_calls();
439
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
440
    $this->assertEqual($calls['rotate'][0][2], 0xffffff, 'Background color was passed correctly');
441
  }
442

    
443
  /**
444
   * Test image effect caching.
445
   */
446
  function testImageEffectsCaching() {
447
    $image_effect_definitions_called = &drupal_static('image_module_test_image_effect_info_alter');
448

    
449
    // First call should grab a fresh copy of the data.
450
    $effects = image_effect_definitions();
451
    $this->assertTrue($image_effect_definitions_called === 1, 'image_effect_definitions() generated data.');
452

    
453
    // Second call should come from cache.
454
    drupal_static_reset('image_effect_definitions');
455
    drupal_static_reset('image_module_test_image_effect_info_alter');
456
    $cached_effects = image_effect_definitions();
457
    $this->assertTrue(is_null($image_effect_definitions_called), 'image_effect_definitions() returned data from cache.');
458

    
459
    $this->assertTrue($effects == $cached_effects, 'Cached effects are the same as generated effects.');
460
  }
461
}
462

    
463
/**
464
 * Tests creation, deletion, and editing of image styles and effects.
465
 */
466
class ImageAdminStylesUnitTest extends ImageFieldTestCase {
467

    
468
  public static function getInfo() {
469
    return array(
470
      'name' => 'Image styles and effects UI configuration',
471
      'description' => 'Tests creation, deletion, and editing of image styles and effects at the UI level.',
472
      'group' => 'Image',
473
    );
474
  }
475

    
476
  /**
477
   * Given an image style, generate an image.
478
   */
479
  function createSampleImage($style) {
480
    static $file_path;
481

    
482
    // First, we need to make sure we have an image in our testing
483
    // file directory. Copy over an image on the first run.
484
    if (!isset($file_path)) {
485
      $files = $this->drupalGetTestFiles('image');
486
      $file = reset($files);
487
      $file_path = file_unmanaged_copy($file->uri);
488
    }
489

    
490
    return image_style_url($style['name'], $file_path) ? $file_path : FALSE;
491
  }
492

    
493
  /**
494
   * Count the number of images currently create for a style.
495
   */
496
  function getImageCount($style) {
497
    return count(file_scan_directory('public://styles/' . $style['name'], '/.*/'));
498
  }
499

    
500
  /**
501
   * Test creating an image style with a numeric name and ensuring it can be
502
   * applied to an image.
503
   */
504
  function testNumericStyleName() {
505
    $style_name = rand();
506
    $style_label = $this->randomString();
507
    $edit = array(
508
      'name' => $style_name,
509
      'label' => $style_label,
510
    );
511
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
512
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
513
    $options = image_style_options();
514
    $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', array('%key' => $style_name)));
515
  }
516

    
517
  /**
518
   * General test to add a style, add/remove/edit effects to it, then delete it.
519
   */
520
  function testStyle() {
521
    // Setup a style to be created and effects to add to it.
522
    $style_name = strtolower($this->randomName(10));
523
    $style_label = $this->randomString();
524
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
525
    $effect_edits = array(
526
      'image_resize' => array(
527
        'data[width]' => 100,
528
        'data[height]' => 101,
529
      ),
530
      'image_scale' => array(
531
        'data[width]' => 110,
532
        'data[height]' => 111,
533
        'data[upscale]' => 1,
534
      ),
535
      'image_scale_and_crop' => array(
536
        'data[width]' => 120,
537
        'data[height]' => 121,
538
      ),
539
      'image_crop' => array(
540
        'data[width]' => 130,
541
        'data[height]' => 131,
542
        'data[anchor]' => 'center-center',
543
      ),
544
      'image_desaturate' => array(
545
        // No options for desaturate.
546
      ),
547
      'image_rotate' => array(
548
        'data[degrees]' => 5,
549
        'data[random]' => 1,
550
        'data[bgcolor]' => '#FFFF00',
551
      ),
552
    );
553

    
554
    // Add style form.
555

    
556
    $edit = array(
557
      'name' => $style_name,
558
      'label' => $style_label,
559
    );
560
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
561
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
562

    
563
    // Add effect form.
564

    
565
    // Add each sample effect to the style.
566
    foreach ($effect_edits as $effect => $edit) {
567
      // Add the effect.
568
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
569
      if (!empty($edit)) {
570
        $this->drupalPost(NULL, $edit, t('Add effect'));
571
      }
572
    }
573

    
574
    // Edit effect form.
575

    
576
    // Revisit each form to make sure the effect was saved.
577
    drupal_static_reset('image_styles');
578
    $style = image_style_load($style_name);
579

    
580
    foreach ($style['effects'] as $ieid => $effect) {
581
      $this->drupalGet($style_path . '/effects/' . $ieid);
582
      foreach ($effect_edits[$effect['name']] as $field => $value) {
583
        $this->assertFieldByName($field, $value, format_string('The %field field in the %effect effect has the correct value of %value.', array('%field' => $field, '%effect' => $effect['name'], '%value' => $value)));
584
      }
585
    }
586

    
587
    // Image style overview form (ordering and renaming).
588

    
589
    // Confirm the order of effects is maintained according to the order we
590
    // added the fields.
591
    $effect_edits_order = array_keys($effect_edits);
592
    $effects_order = array_values($style['effects']);
593
    $order_correct = TRUE;
594
    foreach ($effects_order as $index => $effect) {
595
      if ($effect_edits_order[$index] != $effect['name']) {
596
        $order_correct = FALSE;
597
      }
598
    }
599
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
600

    
601
    // Test the style overview form.
602
    // Change the name of the style and adjust the weights of effects.
603
    $style_name = strtolower($this->randomName(10));
604
    $style_label = $this->randomString();
605
    $weight = count($effect_edits);
606
    $edit = array(
607
      'name' => $style_name,
608
      'label' => $style_label,
609
    );
610
    foreach ($style['effects'] as $ieid => $effect) {
611
      $edit['effects[' . $ieid . '][weight]'] = $weight;
612
      $weight--;
613
    }
614

    
615
    // Create an image to make sure it gets flushed after saving.
616
    $image_path = $this->createSampleImage($style);
617
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
618

    
619
    $this->drupalPost($style_path, $edit, t('Update style'));
620

    
621
    // Note that after changing the style name, the style path is changed.
622
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
623

    
624
    // Check that the URL was updated.
625
    $this->drupalGet($style_path);
626
    $this->assertResponse(200, format_string('Image style %original renamed to %new', array('%original' => $style['label'], '%new' => $style_label)));
627

    
628
    // Check that the image was flushed after updating the style.
629
    // This is especially important when renaming the style. Make sure that
630
    // the old image directory has been deleted.
631
    $this->assertEqual($this->getImageCount($style), 0, format_string('Image style %style was flushed after renaming the style and updating the order of effects.', array('%style' => $style['label'])));
632

    
633
    // Load the style by the new name with the new weights.
634
    drupal_static_reset('image_styles');
635
    $style = image_style_load($style_name, NULL);
636

    
637
    // Confirm the new style order was saved.
638
    $effect_edits_order = array_reverse($effect_edits_order);
639
    $effects_order = array_values($style['effects']);
640
    $order_correct = TRUE;
641
    foreach ($effects_order as $index => $effect) {
642
      if ($effect_edits_order[$index] != $effect['name']) {
643
        $order_correct = FALSE;
644
      }
645
    }
646
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
647

    
648
    // Image effect deletion form.
649

    
650
    // Create an image to make sure it gets flushed after deleting an effect.
651
    $image_path = $this->createSampleImage($style);
652
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
653

    
654
    // Test effect deletion form.
655
    $effect = array_pop($style['effects']);
656
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
657
    $this->assertRaw(t('The image effect %name has been deleted.', array('%name' => $effect['label'])), 'Image effect deleted.');
658

    
659
    // Style deletion form.
660

    
661
    // Delete the style.
662
    $this->drupalPost('admin/config/media/image-styles/delete/' . $style_name, array(), t('Delete'));
663

    
664
    // Confirm the style directory has been removed.
665
    $directory = file_default_scheme() . '://styles/' . $style_name;
666
    $this->assertFalse(is_dir($directory), format_string('Image style %style directory removed on style deletion.', array('%style' => $style['label'])));
667

    
668
    drupal_static_reset('image_styles');
669
    $this->assertFalse(image_style_load($style_name), format_string('Image style %style successfully deleted.', array('%style' => $style['label'])));
670

    
671
  }
672

    
673
  /**
674
   * Test to override, edit, then revert a style.
675
   */
676
  function testDefaultStyle() {
677
    // Setup a style to be created and effects to add to it.
678
    $style_name = 'thumbnail';
679
    $style_label = 'Thumbnail (100x100)';
680
    $edit_path = 'admin/config/media/image-styles/edit/' . $style_name;
681
    $delete_path = 'admin/config/media/image-styles/delete/' . $style_name;
682
    $revert_path = 'admin/config/media/image-styles/revert/' . $style_name;
683

    
684
    // Ensure deleting a default is not possible.
685
    $this->drupalGet($delete_path);
686
    $this->assertText(t('Page not found'), 'Default styles may not be deleted.');
687

    
688
    // Ensure that editing a default is not possible (without overriding).
689
    $this->drupalGet($edit_path);
690
    $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
691
    $this->assertTrue($disabled_field, 'Default styles may not be renamed.');
692
    $this->assertNoField('edit-submit', 'Default styles may not be edited.');
693
    $this->assertNoField('edit-add', 'Default styles may not have new effects added.');
694

    
695
    // Create an image to make sure the default works before overriding.
696
    drupal_static_reset('image_styles');
697
    $style = image_style_load($style_name);
698
    $image_path = $this->createSampleImage($style);
699
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
700

    
701
    // Verify that effects attached to a default style do not have an ieid key.
702
    foreach ($style['effects'] as $effect) {
703
      $this->assertFalse(isset($effect['ieid']), format_string('The %effect effect does not have an ieid.', array('%effect' => $effect['name'])));
704
    }
705

    
706
    // Override the default.
707
    $this->drupalPost($edit_path, array(), t('Override defaults'));
708
    $this->assertRaw(t('The %style style has been overridden, allowing you to change its settings.', array('%style' => $style_label)), 'Default image style may be overridden.');
709

    
710
    // Add sample effect to the overridden style.
711
    $this->drupalPost($edit_path, array('new' => 'image_desaturate'), t('Add'));
712
    drupal_static_reset('image_styles');
713
    $style = image_style_load($style_name);
714

    
715
    // Verify that effects attached to the style have an ieid now.
716
    foreach ($style['effects'] as $effect) {
717
      $this->assertTrue(isset($effect['ieid']), format_string('The %effect effect has an ieid.', array('%effect' => $effect['name'])));
718
    }
719

    
720
    // The style should now have 2 effect, the original scale provided by core
721
    // and the desaturate effect we added in the override.
722
    $effects = array_values($style['effects']);
723
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the overridden style.');
724
    $this->assertEqual($effects[1]['name'], 'image_desaturate', 'The added effect exists in the overridden style.');
725

    
726
    // Check that we are able to rename an overridden style.
727
    $this->drupalGet($edit_path);
728
    $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
729
    $this->assertFalse($disabled_field, 'Overridden styles may be renamed.');
730

    
731
    // Create an image to ensure the override works properly.
732
    $image_path = $this->createSampleImage($style);
733
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
734

    
735
    // Revert the image style.
736
    $this->drupalPost($revert_path, array(), t('Revert'));
737
    drupal_static_reset('image_styles');
738
    $style = image_style_load($style_name);
739

    
740
    // The style should now have the single effect for scale.
741
    $effects = array_values($style['effects']);
742
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the reverted style.');
743
    $this->assertFalse(array_key_exists(1, $effects), 'The added effect has been removed in the reverted style.');
744
  }
745

    
746
  /**
747
   * Test deleting a style and choosing a replacement style.
748
   */
749
  function testStyleReplacement() {
750
    // Create a new style.
751
    $style_name = strtolower($this->randomName(10));
752
    $style_label = $this->randomString();
753
    image_style_save(array('name' => $style_name, 'label' => $style_label));
754
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
755

    
756
    // Create an image field that uses the new style.
757
    $field_name = strtolower($this->randomName(10));
758
    $this->createImageField($field_name, 'article');
759
    $instance = field_info_instance('node', $field_name, 'article');
760
    $instance['display']['default']['type'] = 'image';
761
    $instance['display']['default']['settings']['image_style'] = $style_name;
762
    field_update_instance($instance);
763

    
764
    // Create a new node with an image attached.
765
    $test_image = current($this->drupalGetTestFiles('image'));
766
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
767
    $node = node_load($nid);
768

    
769
    // Test that image is displayed using newly created style.
770
    $this->drupalGet('node/' . $nid);
771
    $this->assertRaw(check_plain(image_style_url($style_name, $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style @style.', array('@style' => $style_name)));
772

    
773
    // Rename the style and make sure the image field is updated.
774
    $new_style_name = strtolower($this->randomName(10));
775
    $new_style_label = $this->randomString();
776
    $edit = array(
777
      'name' => $new_style_name,
778
      'label' => $new_style_label,
779
    );
780
    $this->drupalPost('admin/config/media/image-styles/edit/' . $style_name, $edit, t('Update style'));
781
    $this->assertText(t('Changes to the style have been saved.'), format_string('Style %name was renamed to %new_name.', array('%name' => $style_name, '%new_name' => $new_style_name)));
782
    $this->drupalGet('node/' . $nid);
783
    $this->assertRaw(check_plain(image_style_url($new_style_name, $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
784

    
785
    // Delete the style and choose a replacement style.
786
    $edit = array(
787
      'replacement' => 'thumbnail',
788
    );
789
    $this->drupalPost('admin/config/media/image-styles/delete/' . $new_style_name, $edit, t('Delete'));
790
    $message = t('Style %name was deleted.', array('%name' => $new_style_label));
791
    $this->assertRaw($message, $message);
792

    
793
    $this->drupalGet('node/' . $nid);
794
    $this->assertRaw(check_plain(image_style_url('thumbnail', $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
795
  }
796
}
797

    
798
/**
799
 * Test class to check that formatters and display settings are working.
800
 */
801
class ImageFieldDisplayTestCase extends ImageFieldTestCase {
802
  public static function getInfo() {
803
    return array(
804
      'name' => 'Image field display tests',
805
      'description' => 'Test the display of image fields.',
806
      'group' => 'Image',
807
    );
808
  }
809

    
810
  /**
811
   * Test image formatters on node display for public files.
812
   */
813
  function testImageFieldFormattersPublic() {
814
    $this->_testImageFieldFormatters('public');
815
  }
816

    
817
  /**
818
   * Test image formatters on node display for private files.
819
   */
820
  function testImageFieldFormattersPrivate() {
821
    // Remove access content permission from anonymous users.
822
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access content' => FALSE));
823
    $this->_testImageFieldFormatters('private');
824
  }
825

    
826
  /**
827
   * Test image formatters on node display.
828
   */
829
  function _testImageFieldFormatters($scheme) {
830
    $field_name = strtolower($this->randomName());
831
    $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme));
832
    // Create a new node with an image attached.
833
    $test_image = current($this->drupalGetTestFiles('image'));
834
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
835
    $node = node_load($nid, NULL, TRUE);
836

    
837
    // Test that the default formatter is being used.
838
    $image_uri = $node->{$field_name}[LANGUAGE_NONE][0]['uri'];
839
    $image_info = array(
840
      'path' => $image_uri,
841
      'width' => 40,
842
      'height' => 20,
843
    );
844
    $default_output = theme('image', $image_info);
845
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
846

    
847
    // Test the image linked to file formatter.
848
    $instance = field_info_instance('node', $field_name, 'article');
849
    $instance['display']['default']['type'] = 'image';
850
    $instance['display']['default']['settings']['image_link'] = 'file';
851
    field_update_instance($instance);
852
    $default_output = l(theme('image', $image_info), file_create_url($image_uri), array('html' => TRUE));
853
    $this->drupalGet('node/' . $nid);
854
    $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
855
    // Verify that the image can be downloaded.
856
    $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
857
    if ($scheme == 'private') {
858
      // Only verify HTTP headers when using private scheme and the headers are
859
      // sent by Drupal.
860
      $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
861
      $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'private', 'Cache-Control header was sent.');
862

    
863
      // Log out and try to access the file.
864
      $this->drupalLogout();
865
      $this->drupalGet(file_create_url($image_uri));
866
      $this->assertResponse('403', 'Access denied to original image as anonymous user.');
867

    
868
      // Log in again.
869
      $this->drupalLogin($this->admin_user);
870
    }
871

    
872
    // Test the image linked to content formatter.
873
    $instance['display']['default']['settings']['image_link'] = 'content';
874
    field_update_instance($instance);
875
    $default_output = l(theme('image', $image_info), 'node/' . $nid, array('html' => TRUE, 'attributes' => array('class' => 'active')));
876
    $this->drupalGet('node/' . $nid);
877
    $this->assertRaw($default_output, 'Image linked to content formatter displaying correctly on full node view.');
878

    
879
    // Test the image style 'thumbnail' formatter.
880
    $instance['display']['default']['settings']['image_link'] = '';
881
    $instance['display']['default']['settings']['image_style'] = 'thumbnail';
882
    field_update_instance($instance);
883
    // Ensure the derivative image is generated so we do not have to deal with
884
    // image style callback paths.
885
    $this->drupalGet(image_style_url('thumbnail', $image_uri));
886
    // Need to create the URL again since it will change if clean URLs
887
    // are disabled.
888
    $image_info['path'] = image_style_url('thumbnail', $image_uri);
889
    $image_info['width'] = 100;
890
    $image_info['height'] = 50;
891
    $default_output = theme('image', $image_info);
892
    $this->drupalGet('node/' . $nid);
893
    $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
894

    
895
    if ($scheme == 'private') {
896
      // Log out and try to access the file.
897
      $this->drupalLogout();
898
      $this->drupalGet(image_style_url('thumbnail', $image_uri));
899
      $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
900
    }
901
  }
902

    
903
  /**
904
   * Tests for image field settings.
905
   */
906
  function testImageFieldSettings() {
907
    $test_image = current($this->drupalGetTestFiles('image'));
908
    list(, $test_image_extension) = explode('.', $test_image->filename);
909
    $field_name = strtolower($this->randomName());
910
    $instance_settings = array(
911
      'alt_field' => 1,
912
      'file_extensions' => $test_image_extension,
913
      'max_filesize' => '50 KB',
914
      'max_resolution' => '100x100',
915
      'min_resolution' => '10x10',
916
      'title_field' => 1,
917
    );
918
    $widget_settings = array(
919
      'preview_image_style' => 'medium',
920
    );
921
    $field = $this->createImageField($field_name, 'article', array(), $instance_settings, $widget_settings);
922
    $field['deleted'] = 0;
923
    $table = _field_sql_storage_tablename($field);
924
    $schema = drupal_get_schema($table, TRUE);
925
    $instance = field_info_instance('node', $field_name, 'article');
926

    
927
    $this->drupalGet('node/add/article');
928
    $this->assertText(t('Files must be less than 50 KB.'), 'Image widget max file size is displayed on article form.');
929
    $this->assertText(t('Allowed file types: ' . $test_image_extension . '.'), 'Image widget allowed file types displayed on article form.');
930
    $this->assertText(t('Images must be between 10x10 and 100x100 pixels.'), 'Image widget allowed resolution displayed on article form.');
931

    
932
    // We have to create the article first and then edit it because the alt
933
    // and title fields do not display until the image has been attached.
934
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
935
    $this->drupalGet('node/' . $nid . '/edit');
936
    $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][alt]', '', 'Alt field displayed on article form.');
937
    $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][title]', '', 'Title field displayed on article form.');
938
    // Verify that the attached image is being previewed using the 'medium'
939
    // style.
940
    $node = node_load($nid, NULL, TRUE);
941
    $image_info = array(
942
      'path' => image_style_url('medium', $node->{$field_name}[LANGUAGE_NONE][0]['uri']),
943
      'width' => 220,
944
      'height' => 110,
945
    );
946
    $default_output = theme('image', $image_info);
947
    $this->assertRaw($default_output, "Preview image is displayed using 'medium' style.");
948

    
949
    // Add alt/title fields to the image and verify that they are displayed.
950
    $image_info = array(
951
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
952
      'alt' => $this->randomName(),
953
      'title' => $this->randomName(),
954
      'width' => 40,
955
      'height' => 20,
956
    );
957
    $edit = array(
958
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $image_info['alt'],
959
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $image_info['title'],
960
    );
961
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
962
    $default_output = theme('image', $image_info);
963
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
964

    
965
    // Verify that alt/title longer than allowed results in a validation error.
966
    $test_size = 2000;
967
    $edit = array(
968
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $this->randomName($test_size),
969
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $this->randomName($test_size),
970
    );
971
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
972
    $this->assertRaw(t('Alternate text cannot be longer than %max characters but is currently %length characters long.', array(
973
      '%max' => $schema['fields'][$field_name .'_alt']['length'],
974
      '%length' => $test_size,
975
    )));
976
    $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
977
      '%max' => $schema['fields'][$field_name .'_title']['length'],
978
      '%length' => $test_size,
979
    )));
980
  }
981

    
982
  /**
983
   * Test passing attributes into the image field formatters.
984
   */
985
  function testImageFieldFormatterAttributes() {
986
    $image = theme('image_formatter', array(
987
      'item' => array(
988
        'uri' => 'http://example.com/example.png',
989
        'attributes' => array(
990
          'data-image-field-formatter' => 'testFound',
991
        ),
992
        'alt' => t('Image field formatter attribute test.'),
993
        'title' => t('Image field formatter'),
994
      ),
995
    ));
996
    $this->assertTrue(stripos($image, 'testFound') > 0, 'Image field formatters can have attributes.');
997
  }
998

    
999
  /**
1000
   * Test use of a default image with an image field.
1001
   */
1002
  function testImageFieldDefaultImage() {
1003
    // Create a new image field.
1004
    $field_name = strtolower($this->randomName());
1005
    $this->createImageField($field_name, 'article');
1006

    
1007
    // Create a new node, with no images and verify that no images are
1008
    // displayed.
1009
    $node = $this->drupalCreateNode(array('type' => 'article'));
1010
    $this->drupalGet('node/' . $node->nid);
1011
    // Verify that no image is displayed on the page by checking for the class
1012
    // that would be used on the image field.
1013
    $this->assertNoPattern('<div class="(.*?)field-name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
1014

    
1015
    // Add a default image to the public imagefield instance.
1016
    $images = $this->drupalGetTestFiles('image');
1017
    $edit = array(
1018
      'files[field_settings_default_image]' => drupal_realpath($images[0]->uri),
1019
    );
1020
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
1021
    // Clear field info cache so the new default image is detected.
1022
    field_info_cache_clear();
1023
    $field = field_info_field($field_name);
1024
    $image = file_load($field['settings']['default_image']);
1025
    $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
1026
    $default_output = theme('image', array('path' => $image->uri));
1027
    $this->drupalGet('node/' . $node->nid);
1028
    $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
1029

    
1030
    // Create a node with an image attached and ensure that the default image
1031
    // is not displayed.
1032
    $nid = $this->uploadNodeImage($images[1], $field_name, 'article');
1033
    $node = node_load($nid, NULL, TRUE);
1034
    $image_info = array(
1035
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
1036
      'width' => 40,
1037
      'height' => 20,
1038
    );
1039
    $image_output = theme('image', $image_info);
1040
    $this->drupalGet('node/' . $nid);
1041
    $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
1042
    $this->assertRaw($image_output, 'User supplied image is displayed.');
1043

    
1044
    // Remove default image from the field and make sure it is no longer used.
1045
    $edit = array(
1046
      'field[settings][default_image][fid]' => 0,
1047
    );
1048
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
1049
    // Clear field info cache so the new default image is detected.
1050
    field_info_cache_clear();
1051
    $field = field_info_field($field_name);
1052
    $this->assertFalse($field['settings']['default_image'], 'Default image removed from field.');
1053
    // Create an image field that uses the private:// scheme and test that the
1054
    // default image works as expected.
1055
    $private_field_name = strtolower($this->randomName());
1056
    $this->createImageField($private_field_name, 'article', array('uri_scheme' => 'private'));
1057
    // Add a default image to the new field.
1058
    $edit = array(
1059
      'files[field_settings_default_image]' => drupal_realpath($images[1]->uri),
1060
    );
1061
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $private_field_name, $edit, t('Save settings'));
1062
    $private_field = field_info_field($private_field_name);
1063
    $image = file_load($private_field['settings']['default_image']);
1064
    $this->assertEqual('private', file_uri_scheme($image->uri), 'Default image uses private:// scheme.');
1065
    $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
1066
    // Create a new node with no image attached and ensure that default private
1067
    // image is displayed.
1068
    $node = $this->drupalCreateNode(array('type' => 'article'));
1069
    $default_output = theme('image', array('path' => $image->uri));
1070
    $this->drupalGet('node/' . $node->nid);
1071
    $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');
1072
  }
1073
}
1074

    
1075
/**
1076
 * Test class to check for various validations.
1077
 */
1078
class ImageFieldValidateTestCase extends ImageFieldTestCase {
1079
  public static function getInfo() {
1080
    return array(
1081
      'name' => 'Image field validation tests',
1082
      'description' => 'Tests validation functions such as min/max resolution.',
1083
      'group' => 'Image',
1084
    );
1085
  }
1086

    
1087
  /**
1088
   * Test min/max resolution settings.
1089
   */
1090
  function testResolution() {
1091
    $field_name = strtolower($this->randomName());
1092
    $min_resolution = 50;
1093
    $max_resolution = 100;
1094
    $instance_settings = array(
1095
      'max_resolution' => $max_resolution . 'x' . $max_resolution,
1096
      'min_resolution' => $min_resolution . 'x' . $min_resolution,
1097
    );
1098
    $this->createImageField($field_name, 'article', array(), $instance_settings);
1099

    
1100
    // We want a test image that is too small, and a test image that is too
1101
    // big, so cycle through test image files until we have what we need.
1102
    $image_that_is_too_big = FALSE;
1103
    $image_that_is_too_small = FALSE;
1104
    foreach ($this->drupalGetTestFiles('image') as $image) {
1105
      $info = image_get_info($image->uri);
1106
      if ($info['width'] > $max_resolution) {
1107
        $image_that_is_too_big = $image;
1108
      }
1109
      if ($info['width'] < $min_resolution) {
1110
        $image_that_is_too_small = $image;
1111
      }
1112
      if ($image_that_is_too_small && $image_that_is_too_big) {
1113
        break;
1114
      }
1115
    }
1116
    $nid = $this->uploadNodeImage($image_that_is_too_small, $field_name, 'article');
1117
    $this->assertText(t('The specified file ' . $image_that_is_too_small->filename . ' could not be uploaded. The image is too small; the minimum dimensions are 50x50 pixels.'), 'Node save failed when minimum image resolution was not met.');
1118
    $nid = $this->uploadNodeImage($image_that_is_too_big, $field_name, 'article');
1119
    $this->assertText(t('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.'), 'Image exceeding max resolution was properly resized.');
1120
  }
1121
}
1122

    
1123
/**
1124
 * Tests that images have correct dimensions when styled.
1125
 */
1126
class ImageDimensionsTestCase extends DrupalWebTestCase {
1127

    
1128
  public static function getInfo() {
1129
    return array(
1130
      'name' => 'Image dimensions',
1131
      'description' => 'Tests that images have correct dimensions when styled.',
1132
      'group' => 'Image',
1133
    );
1134
  }
1135

    
1136
  function setUp() {
1137
    parent::setUp('image_module_test');
1138
  }
1139

    
1140
  /**
1141
   * Test styled image dimensions cumulatively.
1142
   */
1143
  function testImageDimensions() {
1144
    // Create a working copy of the file.
1145
    $files = $this->drupalGetTestFiles('image');
1146
    $file = reset($files);
1147
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1148

    
1149
    // Create a style.
1150
    $style = image_style_save(array('name' => 'test', 'label' => 'Test'));
1151
    $generated_uri = 'public://styles/test/public/'. drupal_basename($original_uri);
1152
    $url = image_style_url('test', $original_uri);
1153

    
1154
    $variables = array(
1155
      'style_name' => 'test',
1156
      'path' => $original_uri,
1157
      'width' => 40,
1158
      'height' => 20,
1159
    );
1160

    
1161
    // Scale an image that is wider than it is high.
1162
    $effect = array(
1163
      'name' => 'image_scale',
1164
      'data' => array(
1165
        'width' => 120,
1166
        'height' => 90,
1167
        'upscale' => TRUE,
1168
      ),
1169
      'isid' => $style['isid'],
1170
    );
1171

    
1172
    image_effect_save($effect);
1173
    $img_tag = theme_image_style($variables);
1174
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="120" height="60" alt="" />', 'Expected img tag was found.');
1175
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1176
    $this->drupalGet($url);
1177
    $this->assertResponse(200, 'Image was generated at the URL.');
1178
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1179
    $image_info = image_get_info($generated_uri);
1180
    $this->assertEqual($image_info['width'], 120, 'Expected width was found.');
1181
    $this->assertEqual($image_info['height'], 60, 'Expected height was found.');
1182

    
1183
    // Rotate 90 degrees anticlockwise.
1184
    $effect = array(
1185
      'name' => 'image_rotate',
1186
      'data' => array(
1187
        'degrees' => -90,
1188
        'random' => FALSE,
1189
      ),
1190
      'isid' => $style['isid'],
1191
    );
1192

    
1193
    image_effect_save($effect);
1194
    $img_tag = theme_image_style($variables);
1195
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="60" height="120" alt="" />', 'Expected img tag was found.');
1196
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1197
    $this->drupalGet($url);
1198
    $this->assertResponse(200, 'Image was generated at the URL.');
1199
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1200
    $image_info = image_get_info($generated_uri);
1201
    $this->assertEqual($image_info['width'], 60, 'Expected width was found.');
1202
    $this->assertEqual($image_info['height'], 120, 'Expected height was found.');
1203

    
1204
    // Scale an image that is higher than it is wide (rotated by previous effect).
1205
    $effect = array(
1206
      'name' => 'image_scale',
1207
      'data' => array(
1208
        'width' => 120,
1209
        'height' => 90,
1210
        'upscale' => TRUE,
1211
      ),
1212
      'isid' => $style['isid'],
1213
    );
1214

    
1215
    image_effect_save($effect);
1216
    $img_tag = theme_image_style($variables);
1217
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1218
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1219
    $this->drupalGet($url);
1220
    $this->assertResponse(200, 'Image was generated at the URL.');
1221
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1222
    $image_info = image_get_info($generated_uri);
1223
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1224
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1225

    
1226
    // Test upscale disabled.
1227
    $effect = array(
1228
      'name' => 'image_scale',
1229
      'data' => array(
1230
        'width' => 400,
1231
        'height' => 200,
1232
        'upscale' => FALSE,
1233
      ),
1234
      'isid' => $style['isid'],
1235
    );
1236

    
1237
    image_effect_save($effect);
1238
    $img_tag = theme_image_style($variables);
1239
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1240
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1241
    $this->drupalGet($url);
1242
    $this->assertResponse(200, 'Image was generated at the URL.');
1243
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1244
    $image_info = image_get_info($generated_uri);
1245
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1246
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1247

    
1248
    // Add a desaturate effect.
1249
    $effect = array(
1250
      'name' => 'image_desaturate',
1251
      'data' => array(),
1252
      'isid' => $style['isid'],
1253
    );
1254

    
1255
    image_effect_save($effect);
1256
    $img_tag = theme_image_style($variables);
1257
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1258
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1259
    $this->drupalGet($url);
1260
    $this->assertResponse(200, 'Image was generated at the URL.');
1261
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1262
    $image_info = image_get_info($generated_uri);
1263
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1264
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1265

    
1266
    // Add a random rotate effect.
1267
    $effect = array(
1268
      'name' => 'image_rotate',
1269
      'data' => array(
1270
        'degrees' => 180,
1271
        'random' => TRUE,
1272
      ),
1273
      'isid' => $style['isid'],
1274
    );
1275

    
1276
    image_effect_save($effect);
1277
    $img_tag = theme_image_style($variables);
1278
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1279
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1280
    $this->drupalGet($url);
1281
    $this->assertResponse(200, 'Image was generated at the URL.');
1282
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1283

    
1284

    
1285
    // Add a crop effect.
1286
    $effect = array(
1287
      'name' => 'image_crop',
1288
      'data' => array(
1289
        'width' => 30,
1290
        'height' => 30,
1291
        'anchor' => 'center-center',
1292
      ),
1293
      'isid' => $style['isid'],
1294
    );
1295

    
1296
    image_effect_save($effect);
1297
    $img_tag = theme_image_style($variables);
1298
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="30" height="30" alt="" />', 'Expected img tag was found.');
1299
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1300
    $this->drupalGet($url);
1301
    $this->assertResponse(200, 'Image was generated at the URL.');
1302
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1303
    $image_info = image_get_info($generated_uri);
1304
    $this->assertEqual($image_info['width'], 30, 'Expected width was found.');
1305
    $this->assertEqual($image_info['height'], 30, 'Expected height was found.');
1306

    
1307
    // Rotate to a non-multiple of 90 degrees.
1308
    $effect = array(
1309
      'name' => 'image_rotate',
1310
      'data' => array(
1311
        'degrees' => 57,
1312
        'random' => FALSE,
1313
      ),
1314
      'isid' => $style['isid'],
1315
    );
1316

    
1317
    $effect = image_effect_save($effect);
1318
    $img_tag = theme_image_style($variables);
1319
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1320
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1321
    $this->drupalGet($url);
1322
    $this->assertResponse(200, 'Image was generated at the URL.');
1323
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1324

    
1325
    image_effect_delete($effect);
1326

    
1327
    // Ensure that an effect with no dimensions callback unsets the dimensions.
1328
    // This ensures compatibility with 7.0 contrib modules.
1329
    $effect = array(
1330
      'name' => 'image_module_test_null',
1331
      'data' => array(),
1332
      'isid' => $style['isid'],
1333
    );
1334

    
1335
    image_effect_save($effect);
1336
    $img_tag = theme_image_style($variables);
1337
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1338
  }
1339
}
1340

    
1341
/**
1342
 * Tests image_dimensions_scale().
1343
 */
1344
class ImageDimensionsScaleTestCase extends DrupalUnitTestCase {
1345
  public static function getInfo() {
1346
    return array(
1347
      'name' => 'image_dimensions_scale()',
1348
      'description' => 'Tests all control flow branches in image_dimensions_scale().',
1349
      'group' => 'Image',
1350
    );
1351
  }
1352

    
1353
  /**
1354
   * Tests all control flow branches in image_dimensions_scale().
1355
   */
1356
  function testImageDimensionsScale() {
1357
    // Define input / output datasets to test different branch conditions.
1358
    $test = array();
1359

    
1360
    // Test branch conditions:
1361
    // - No height.
1362
    // - Upscale, don't need to upscale.
1363
    $tests[] = array(
1364
      'input' => array(
1365
        'dimensions' => array(
1366
          'width' => 1000,
1367
          'height' => 2000,
1368
        ),
1369
        'width' => 200,
1370
        'height' => NULL,
1371
        'upscale' => TRUE,
1372
      ),
1373
      'output' => array(
1374
        'dimensions' => array(
1375
          'width' => 200,
1376
          'height' => 400,
1377
        ),
1378
        'return_value' => TRUE,
1379
      ),
1380
    );
1381

    
1382
    // Test branch conditions:
1383
    // - No width.
1384
    // - Don't upscale, don't need to upscale.
1385
    $tests[] = array(
1386
      'input' => array(
1387
        'dimensions' => array(
1388
          'width' => 1000,
1389
          'height' => 800,
1390
        ),
1391
        'width' => NULL,
1392
        'height' => 140,
1393
        'upscale' => FALSE,
1394
      ),
1395
      'output' => array(
1396
        'dimensions' => array(
1397
          'width' => 175,
1398
          'height' => 140,
1399
        ),
1400
        'return_value' => TRUE,
1401
      ),
1402
    );
1403

    
1404
    // Test branch conditions:
1405
    // - Source aspect ratio greater than target.
1406
    // - Upscale, need to upscale.
1407
    $tests[] = array(
1408
      'input' => array(
1409
        'dimensions' => array(
1410
          'width' => 8,
1411
          'height' => 20,
1412
        ),
1413
        'width' => 200,
1414
        'height' => 140,
1415
        'upscale' => TRUE,
1416
      ),
1417
      'output' => array(
1418
        'dimensions' => array(
1419
          'width' => 56,
1420
          'height' => 140,
1421
        ),
1422
        'return_value' => TRUE,
1423
      ),
1424
    );
1425

    
1426
    // Test branch condition: target aspect ratio greater than source.
1427
    $tests[] = array(
1428
      'input' => array(
1429
        'dimensions' => array(
1430
          'width' => 2000,
1431
          'height' => 800,
1432
        ),
1433
        'width' => 200,
1434
        'height' => 140,
1435
        'upscale' => FALSE,
1436
      ),
1437
      'output' => array(
1438
        'dimensions' => array(
1439
          'width' => 200,
1440
          'height' => 80,
1441
        ),
1442
        'return_value' => TRUE,
1443
      ),
1444
    );
1445

    
1446
    // Test branch condition: don't upscale, need to upscale.
1447
    $tests[] = array(
1448
      'input' => array(
1449
        'dimensions' => array(
1450
          'width' => 100,
1451
          'height' => 50,
1452
        ),
1453
        'width' => 200,
1454
        'height' => 140,
1455
        'upscale' => FALSE,
1456
      ),
1457
      'output' => array(
1458
        'dimensions' => array(
1459
          'width' => 100,
1460
          'height' => 50,
1461
        ),
1462
        'return_value' => FALSE,
1463
      ),
1464
    );
1465

    
1466
    foreach ($tests as $test) {
1467
      // Process the test dataset.
1468
      $return_value = image_dimensions_scale($test['input']['dimensions'], $test['input']['width'], $test['input']['height'], $test['input']['upscale']);
1469

    
1470
      // Check the width.
1471
      $this->assertEqual($test['output']['dimensions']['width'], $test['input']['dimensions']['width'], format_string('Computed width (@computed_width) equals expected width (@expected_width)', array('@computed_width' => $test['output']['dimensions']['width'], '@expected_width' => $test['input']['dimensions']['width'])));
1472

    
1473
      // Check the height.
1474
      $this->assertEqual($test['output']['dimensions']['height'], $test['input']['dimensions']['height'], format_string('Computed height (@computed_height) equals expected height (@expected_height)', array('@computed_height' => $test['output']['dimensions']['height'], '@expected_height' => $test['input']['dimensions']['height'])));
1475

    
1476
      // Check the return value.
1477
      $this->assertEqual($test['output']['return_value'], $return_value, 'Correct return value.');
1478
    }
1479
  }
1480
}
1481

    
1482
/**
1483
 * Tests default image settings.
1484
 */
1485
class ImageFieldDefaultImagesTestCase extends ImageFieldTestCase {
1486

    
1487
  public static function getInfo() {
1488
    return array(
1489
      'name' => 'Image field default images tests',
1490
      'description' => 'Tests setting up default images both to the field and field instance.',
1491
      'group' => 'Image',
1492
    );
1493
  }
1494

    
1495
  function setUp() {
1496
    parent::setUp(array('field_ui'));
1497
  }
1498

    
1499
  /**
1500
   * Tests CRUD for fields and fields instances with default images.
1501
   */
1502
  function testDefaultImages() {
1503
    // Create files to use as the default images.
1504
    $files = $this->drupalGetTestFiles('image');
1505
    $default_images = array();
1506
    foreach (array('field', 'instance', 'instance2', 'field_new', 'instance_new') as $image_target) {
1507
      $file = array_pop($files);
1508
      $file = file_save($file);
1509
      $default_images[$image_target] = $file;
1510
    }
1511

    
1512
    // Create an image field and add an instance to the article content type.
1513
    $field_name = strtolower($this->randomName());
1514
    $field_settings = array(
1515
      'default_image' => $default_images['field']->fid,
1516
    );
1517
    $instance_settings = array(
1518
      'default_image' => $default_images['instance']->fid,
1519
    );
1520
    $widget_settings = array(
1521
      'preview_image_style' => 'medium',
1522
    );
1523
    $this->createImageField($field_name, 'article', $field_settings, $instance_settings, $widget_settings);
1524
    $field = field_info_field($field_name);
1525
    $instance = field_info_instance('node', $field_name, 'article');
1526

    
1527
    // Add another instance with another default image to the page content type.
1528
    $instance2 = array_merge($instance, array(
1529
      'bundle' => 'page',
1530
      'settings' => array(
1531
        'default_image' => $default_images['instance2']->fid,
1532
      ),
1533
    ));
1534
    field_create_instance($instance2);
1535
    $instance2 = field_info_instance('node', $field_name, 'page');
1536

    
1537

    
1538
    // Confirm the defaults are present on the article field admin form.
1539
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1540
    $this->assertFieldByXpath(
1541
      '//input[@name="field[settings][default_image][fid]"]',
1542
      $default_images['field']->fid,
1543
      format_string(
1544
        'Article image field default equals expected file ID of @fid.',
1545
        array('@fid' => $default_images['field']->fid)
1546
      )
1547
    );
1548
    $this->assertFieldByXpath(
1549
      '//input[@name="instance[settings][default_image][fid]"]',
1550
      $default_images['instance']->fid,
1551
      format_string(
1552
        'Article image field instance default equals expected file ID of @fid.',
1553
        array('@fid' => $default_images['instance']->fid)
1554
      )
1555
    );
1556

    
1557
    // Confirm the defaults are present on the page field admin form.
1558
    $this->drupalGet("admin/structure/types/manage/page/fields/$field_name");
1559
    $this->assertFieldByXpath(
1560
      '//input[@name="field[settings][default_image][fid]"]',
1561
      $default_images['field']->fid,
1562
      format_string(
1563
        'Page image field default equals expected file ID of @fid.',
1564
        array('@fid' => $default_images['field']->fid)
1565
      )
1566
    );
1567
    $this->assertFieldByXpath(
1568
      '//input[@name="instance[settings][default_image][fid]"]',
1569
      $default_images['instance2']->fid,
1570
      format_string(
1571
        'Page image field instance default equals expected file ID of @fid.',
1572
        array('@fid' => $default_images['instance2']->fid)
1573
      )
1574
    );
1575

    
1576
    // Confirm that the image default is shown for a new article node.
1577
    $article = $this->drupalCreateNode(array('type' => 'article'));
1578
    $article_built = node_view($article);
1579
    $this->assertEqual(
1580
      $article_built[$field_name]['#items'][0]['fid'],
1581
      $default_images['instance']->fid,
1582
      format_string(
1583
        'A new article node without an image has the expected default image file ID of @fid.',
1584
        array('@fid' => $default_images['instance']->fid)
1585
      )
1586
    );
1587

    
1588
    // Confirm that the image default is shown for a new page node.
1589
    $page = $this->drupalCreateNode(array('type' => 'page'));
1590
    $page_built = node_view($page);
1591
    $this->assertEqual(
1592
      $page_built[$field_name]['#items'][0]['fid'],
1593
      $default_images['instance2']->fid,
1594
      format_string(
1595
        'A new page node without an image has the expected default image file ID of @fid.',
1596
        array('@fid' => $default_images['instance2']->fid)
1597
      )
1598
    );
1599

    
1600
    // Upload a new default for the field.
1601
    $field['settings']['default_image'] = $default_images['field_new']->fid;
1602
    field_update_field($field);
1603

    
1604
    // Confirm that the new field default is used on the article admin form.
1605
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1606
    $this->assertFieldByXpath(
1607
      '//input[@name="field[settings][default_image][fid]"]',
1608
      $default_images['field_new']->fid,
1609
      format_string(
1610
        'Updated image field default equals expected file ID of @fid.',
1611
        array('@fid' => $default_images['field_new']->fid)
1612
      )
1613
    );
1614

    
1615
    // Reload the nodes and confirm the field instance defaults are used.
1616
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1617
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1618
    $this->assertEqual(
1619
      $article_built[$field_name]['#items'][0]['fid'],
1620
      $default_images['instance']->fid,
1621
      format_string(
1622
        'An existing article node without an image has the expected default image file ID of @fid.',
1623
        array('@fid' => $default_images['instance']->fid)
1624
      )
1625
    );
1626
    $this->assertEqual(
1627
      $page_built[$field_name]['#items'][0]['fid'],
1628
      $default_images['instance2']->fid,
1629
      format_string(
1630
        'An existing page node without an image has the expected default image file ID of @fid.',
1631
        array('@fid' => $default_images['instance2']->fid)
1632
      )
1633
    );
1634

    
1635
    // Upload a new default for the article's field instance.
1636
    $instance['settings']['default_image'] = $default_images['instance_new']->fid;
1637
    field_update_instance($instance);
1638

    
1639
    // Confirm the new field instance default is used on the article field
1640
    // admin form.
1641
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1642
    $this->assertFieldByXpath(
1643
      '//input[@name="instance[settings][default_image][fid]"]',
1644
      $default_images['instance_new']->fid,
1645
      format_string(
1646
        'Updated article image field instance default equals expected file ID of @fid.',
1647
        array('@fid' => $default_images['instance_new']->fid)
1648
      )
1649
    );
1650

    
1651
    // Reload the nodes.
1652
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1653
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1654

    
1655
    // Confirm the article uses the new default.
1656
    $this->assertEqual(
1657
      $article_built[$field_name]['#items'][0]['fid'],
1658
      $default_images['instance_new']->fid,
1659
      format_string(
1660
        'An existing article node without an image has the expected default image file ID of @fid.',
1661
        array('@fid' => $default_images['instance_new']->fid)
1662
      )
1663
    );
1664
    // Confirm the page remains unchanged.
1665
    $this->assertEqual(
1666
      $page_built[$field_name]['#items'][0]['fid'],
1667
      $default_images['instance2']->fid,
1668
      format_string(
1669
        'An existing page node without an image has the expected default image file ID of @fid.',
1670
        array('@fid' => $default_images['instance2']->fid)
1671
      )
1672
    );
1673

    
1674
    // Remove the instance default from articles.
1675
    $instance['settings']['default_image'] = NULL;
1676
    field_update_instance($instance);
1677

    
1678
    // Confirm the article field instance default has been removed.
1679
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1680
    $this->assertFieldByXpath(
1681
      '//input[@name="instance[settings][default_image][fid]"]',
1682
      '',
1683
      'Updated article image field instance default has been successfully removed.'
1684
    );
1685

    
1686
    // Reload the nodes.
1687
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1688
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1689
    // Confirm the article uses the new field (not instance) default.
1690
    $this->assertEqual(
1691
      $article_built[$field_name]['#items'][0]['fid'],
1692
      $default_images['field_new']->fid,
1693
      format_string(
1694
        'An existing article node without an image has the expected default image file ID of @fid.',
1695
        array('@fid' => $default_images['field_new']->fid)
1696
      )
1697
    );
1698
    // Confirm the page remains unchanged.
1699
    $this->assertEqual(
1700
      $page_built[$field_name]['#items'][0]['fid'],
1701
      $default_images['instance2']->fid,
1702
      format_string(
1703
        'An existing page node without an image has the expected default image file ID of @fid.',
1704
        array('@fid' => $default_images['instance2']->fid)
1705
      )
1706
    );
1707
  }
1708

    
1709
}
1710

    
1711
/**
1712
 * Tests image theme functions.
1713
 */
1714
class ImageThemeFunctionWebTestCase extends DrupalWebTestCase {
1715

    
1716
  public static function getInfo() {
1717
    return array(
1718
      'name' => 'Image theme functions',
1719
      'description' => 'Test that the image theme functions work correctly.',
1720
      'group' => 'Image',
1721
    );
1722
  }
1723

    
1724
  function setUp() {
1725
    parent::setUp(array('image'));
1726
  }
1727

    
1728
  /**
1729
   * Tests usage of the image field formatters.
1730
   */
1731
  function testImageFormatterTheme() {
1732
    // Create an image.
1733
    $files = $this->drupalGetTestFiles('image');
1734
    $file = reset($files);
1735
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1736

    
1737
    // Create a style.
1738
    image_style_save(array('name' => 'test', 'label' => 'Test'));
1739
    $url = image_style_url('test', $original_uri);
1740

    
1741
    // Test using theme_image_formatter() without an image title, alt text, or
1742
    // link options.
1743
    $path = $this->randomName();
1744
    $element = array(
1745
      '#theme' => 'image_formatter',
1746
      '#image_style' => 'test',
1747
      '#item' => array(
1748
        'uri' => $original_uri,
1749
      ),
1750
      '#path' => array(
1751
        'path' => $path,
1752
      ),
1753
    );
1754
    $rendered_element = render($element);
1755
    $expected_result = '<a href="' . url($path) . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1756
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders without title, alt, or path options.');
1757

    
1758
    // Link the image to a fragment on the page, and not a full URL.
1759
    $fragment = $this->randomName();
1760
    $element['#path']['path'] = '';
1761
    $element['#path']['options'] = array(
1762
      'external' => TRUE,
1763
      'fragment' => $fragment,
1764
    );
1765
    $rendered_element = render($element);
1766
    $expected_result = '<a href="#' . $fragment . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1767
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders a link fragment.');
1768
  }
1769

    
1770
}
1771

    
1772
/**
1773
 * Tests flushing of image styles.
1774
 */
1775
class ImageStyleFlushTest extends ImageFieldTestCase {
1776

    
1777
  public static function getInfo() {
1778
    return array(
1779
      'name' => 'Image style flushing',
1780
      'description' => 'Tests flushing of image styles.',
1781
      'group' => 'Image',
1782
    );
1783
  }
1784

    
1785
  /**
1786
   * Given an image style and a wrapper, generate an image.
1787
   */
1788
  function createSampleImage($style, $wrapper) {
1789
    static $file;
1790

    
1791
    if (!isset($file)) {
1792
      $files = $this->drupalGetTestFiles('image');
1793
      $file = reset($files);
1794
    }
1795

    
1796
    // Make sure we have an image in our wrapper testing file directory.
1797
    $source_uri = file_unmanaged_copy($file->uri, $wrapper . '://');
1798
    // Build the derivative image.
1799
    $derivative_uri = image_style_path($style['name'], $source_uri);
1800
    $derivative = image_style_create_derivative($style, $source_uri, $derivative_uri);
1801

    
1802
    return $derivative ? $derivative_uri : FALSE;
1803
  }
1804

    
1805
  /**
1806
   * Count the number of images currently created for a style in a wrapper.
1807
   */
1808
  function getImageCount($style, $wrapper) {
1809
    return count(file_scan_directory($wrapper . '://styles/' . $style['name'], '/.*/'));
1810
  }
1811

    
1812
  /**
1813
   * General test to flush a style.
1814
   */
1815
  function testFlush() {
1816

    
1817
    // Setup a style to be created and effects to add to it.
1818
    $style_name = strtolower($this->randomName(10));
1819
    $style_label = $this->randomString();
1820
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
1821
    $effect_edits = array(
1822
      'image_resize' => array(
1823
        'data[width]' => 100,
1824
        'data[height]' => 101,
1825
      ),
1826
      'image_scale' => array(
1827
        'data[width]' => 110,
1828
        'data[height]' => 111,
1829
        'data[upscale]' => 1,
1830
      ),
1831
    );
1832

    
1833
    // Add style form.
1834
    $edit = array(
1835
      'name' => $style_name,
1836
      'label' => $style_label,
1837
    );
1838
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
1839
    // Add each sample effect to the style.
1840
    foreach ($effect_edits as $effect => $edit) {
1841
      // Add the effect.
1842
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
1843
      if (!empty($edit)) {
1844
        $this->drupalPost(NULL, $edit, t('Add effect'));
1845
      }
1846
    }
1847

    
1848
    // Load the saved image style.
1849
    $style = image_style_load($style_name);
1850

    
1851
    // Create an image for the 'public' wrapper.
1852
    $image_path = $this->createSampleImage($style, 'public');
1853
    // Expecting to find 2 images, one is the sample.png image shown in
1854
    // image style preview.
1855
    $this->assertEqual($this->getImageCount($style, 'public'), 2, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
1856

    
1857
    // Create an image for the 'private' wrapper.
1858
    $image_path = $this->createSampleImage($style, 'private');
1859
    $this->assertEqual($this->getImageCount($style, 'private'), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
1860

    
1861
    // Remove the 'image_scale' effect and updates the style, which in turn
1862
    // forces an image style flush.
1863
    $effect = array_pop($style['effects']);
1864
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
1865
    $this->assertResponse(200);
1866
    $this->drupalPost($style_path, array(), t('Update style'));
1867
    $this->assertResponse(200);
1868

    
1869
    // Post flush, expected 1 image in the 'public' wrapper (sample.png).
1870
    $this->assertEqual($this->getImageCount($style, 'public'), 1, format_string('Image style %style flushed correctly for %wrapper wrapper.', array('%style' => $style['name'], '%wrapper' => 'public')));
1871

    
1872
    // Post flush, expected no image in the 'private' wrapper.
1873
    $this->assertEqual($this->getImageCount($style, 'private'), 0, format_string('Image style %style flushed correctly for %wrapper wrapper.', array('%style' => $style['name'], '%wrapper' => 'private')));
1874
  }
1875
}