Projet

Général

Profil

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

root / htmltest / modules / image / image.test @ 85ad3d82

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 image_style_url().
178
   */
179
  function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FALSE) {
180
    // Make the default scheme neither "public" nor "private" to verify the
181
    // functions work for other than the default scheme.
182
    variable_set('file_default_scheme', 'temporary');
183
    variable_set('clean_url', $clean_url);
184

    
185
    // Create the directories for the styles.
186
    $directory = $scheme . '://styles/' . $this->style_name;
187
    $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
188
    $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
189

    
190
    // Create a working copy of the file.
191
    $files = $this->drupalGetTestFiles('image');
192
    $file = array_shift($files);
193
    $image_info = image_get_info($file->uri);
194
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
195
    // Let the image_module_test module know about this file, so it can claim
196
    // ownership in hook_file_download().
197
    variable_set('image_module_test_file_download', $original_uri);
198
    $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
199

    
200
    // Get the URL of a file that has not been generated and try to create it.
201
    $generated_uri = image_style_path($this->style_name, $original_uri);
202
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
203
    $generate_url = image_style_url($this->style_name, $original_uri);
204

    
205
    // Ensure that the tests still pass when the file is generated by accessing
206
    // a poorly constructed (but still valid) file URL that has an extra slash
207
    // in it.
208
    if ($extra_slash) {
209
      $modified_uri = str_replace('://', ':///', $original_uri);
210
      $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
211
      $generate_url = image_style_url($this->style_name, $modified_uri);
212
    }
213

    
214
    if (!$clean_url) {
215
      $this->assertTrue(strpos($generate_url, '?q=') !== FALSE, 'When using non-clean URLS, the system path contains the query string.');
216
    }
217
    // Add some extra chars to the token.
218
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
219
    $this->assertResponse(403, 'Image was inaccessible at the URL with an invalid token.');
220
    // Change the parameter name so the token is missing.
221
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
222
    $this->assertResponse(403, 'Image was inaccessible at the URL with a missing token.');
223

    
224
    // Check that the generated URL is the same when we pass in a relative path
225
    // rather than a URI. We need to temporarily switch the default scheme to
226
    // match the desired scheme before testing this, then switch it back to the
227
    // "temporary" scheme used throughout this test afterwards.
228
    variable_set('file_default_scheme', $scheme);
229
    $relative_path = file_uri_target($original_uri);
230
    $generate_url_from_relative_path = image_style_url($this->style_name, $relative_path);
231
    $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.');
232
    variable_set('file_default_scheme', 'temporary');
233

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

    
247
      // Make sure that a second request to the already existing derivate works
248
      // too.
249
      $this->drupalGet($generate_url);
250
      $this->assertResponse(200, 'Image was generated at the URL.');
251

    
252
      // Make sure that access is denied for existing style files if we do not
253
      // have access.
254
      variable_del('image_module_test_file_download');
255
      $this->drupalGet($generate_url);
256
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
257

    
258
      // Repeat this with a different file that we do not have access to and
259
      // make sure that access is denied.
260
      $file_noaccess = array_shift($files);
261
      $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
262
      $generated_uri_noaccess = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/'. drupal_basename($original_uri_noaccess);
263
      $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
264
      $generate_url_noaccess = image_style_url($this->style_name, $original_uri_noaccess);
265

    
266
      $this->drupalGet($generate_url_noaccess);
267
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
268
      // Verify that images are not appended to the response. Currently this test only uses PNG images.
269
      if (strpos($generate_url, '.png') === FALSE ) {
270
        $this->fail('Confirming that private image styles are not appended require PNG file.');
271
      }
272
      else {
273
        // Check for PNG-Signature (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2) in the
274
        // response body.
275
        $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.');
276
      }
277
    }
278
    elseif ($clean_url) {
279
      // Add some extra chars to the token.
280
      $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
281
      $this->assertResponse(200, 'Existing image was accessible at the URL with an invalid token.');
282
    }
283

    
284
    // Allow insecure image derivatives to be created for the remainder of this
285
    // test.
286
    variable_set('image_allow_insecure_derivatives', TRUE);
287

    
288
    // Create another working copy of the file.
289
    $files = $this->drupalGetTestFiles('image');
290
    $file = array_shift($files);
291
    $image_info = image_get_info($file->uri);
292
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
293
    // Let the image_module_test module know about this file, so it can claim
294
    // ownership in hook_file_download().
295
    variable_set('image_module_test_file_download', $original_uri);
296

    
297
    // Get the URL of a file that has not been generated and try to create it.
298
    $generated_uri = image_style_path($this->style_name, $original_uri);
299
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
300
    $generate_url = image_style_url($this->style_name, $original_uri);
301

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

    
306
    // Check that a security token is still required when generating a second
307
    // image derivative using the first one as a source.
308
    $nested_uri = image_style_path($this->style_name, $generated_uri);
309
    $nested_url = image_style_url($this->style_name, $generated_uri);
310
    $nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $nested_url);
311
    $this->drupalGet($nested_url_with_wrong_token);
312
    $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token.');
313
    // Check that this restriction cannot be bypassed by adding extra slashes
314
    // to the URL.
315
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
316
    $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.');
317
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '/\styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
318
    $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.');
319
    // Make sure the image can still be generated if a correct token is used.
320
    $this->drupalGet($nested_url);
321
    $this->assertResponse(200, 'Image was accessible when a correct token was provided in the URL.');
322

    
323
    // Check that requesting a nonexistent image does not create any new
324
    // directories in the file system.
325
    $directory = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/' . $this->randomName();
326
    $this->drupalGet(file_create_url($directory . '/' . $this->randomName()));
327
    $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
328
  }
329
}
330

    
331
/**
332
 * Use the image_test.module's mock toolkit to ensure that the effects are
333
 * properly passing parameters to the image toolkit.
334
 */
335
class ImageEffectsUnitTest extends ImageToolkitTestCase {
336
  public static function getInfo() {
337
    return array(
338
      'name' => 'Image effects',
339
      'description' => 'Test that the image effects pass parameters to the toolkit correctly.',
340
      'group' => 'Image',
341
    );
342
  }
343

    
344
  function setUp() {
345
    parent::setUp('image_module_test');
346
    module_load_include('inc', 'image', 'image.effects');
347
  }
348

    
349
  /**
350
   * Test the image_resize_effect() function.
351
   */
352
  function testResizeEffect() {
353
    $this->assertTrue(image_resize_effect($this->image, array('width' => 1, 'height' => 2)), 'Function returned the expected value.');
354
    $this->assertToolkitOperationsCalled(array('resize'));
355

    
356
    // Check the parameters.
357
    $calls = image_test_get_all_calls();
358
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
359
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
360
  }
361

    
362
  /**
363
   * Test the image_scale_effect() function.
364
   */
365
  function testScaleEffect() {
366
    // @todo: need to test upscaling.
367
    $this->assertTrue(image_scale_effect($this->image, array('width' => 10, 'height' => 10)), 'Function returned the expected value.');
368
    $this->assertToolkitOperationsCalled(array('resize'));
369

    
370
    // Check the parameters.
371
    $calls = image_test_get_all_calls();
372
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
373
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
374
  }
375

    
376
  /**
377
   * Test the image_crop_effect() function.
378
   */
379
  function testCropEffect() {
380
    // @todo should test the keyword offsets.
381
    $this->assertTrue(image_crop_effect($this->image, array('anchor' => 'top-1', 'width' => 3, 'height' => 4)), 'Function returned the expected value.');
382
    $this->assertToolkitOperationsCalled(array('crop'));
383

    
384
    // Check the parameters.
385
    $calls = image_test_get_all_calls();
386
    $this->assertEqual($calls['crop'][0][1], 0, 'X was passed correctly');
387
    $this->assertEqual($calls['crop'][0][2], 1, 'Y was passed correctly');
388
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
389
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
390
  }
391

    
392
  /**
393
   * Test the image_scale_and_crop_effect() function.
394
   */
395
  function testScaleAndCropEffect() {
396
    $this->assertTrue(image_scale_and_crop_effect($this->image, array('width' => 5, 'height' => 10)), 'Function returned the expected value.');
397
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));
398

    
399
    // Check the parameters.
400
    $calls = image_test_get_all_calls();
401
    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
402
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
403
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
404
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
405
  }
406

    
407
  /**
408
   * Test the image_desaturate_effect() function.
409
   */
410
  function testDesaturateEffect() {
411
    $this->assertTrue(image_desaturate_effect($this->image, array()), 'Function returned the expected value.');
412
    $this->assertToolkitOperationsCalled(array('desaturate'));
413

    
414
    // Check the parameters.
415
    $calls = image_test_get_all_calls();
416
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
417
  }
418

    
419
  /**
420
   * Test the image_rotate_effect() function.
421
   */
422
  function testRotateEffect() {
423
    // @todo: need to test with 'random' => TRUE
424
    $this->assertTrue(image_rotate_effect($this->image, array('degrees' => 90, 'bgcolor' => '#fff')), 'Function returned the expected value.');
425
    $this->assertToolkitOperationsCalled(array('rotate'));
426

    
427
    // Check the parameters.
428
    $calls = image_test_get_all_calls();
429
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
430
    $this->assertEqual($calls['rotate'][0][2], 0xffffff, 'Background color was passed correctly');
431
  }
432

    
433
  /**
434
   * Test image effect caching.
435
   */
436
  function testImageEffectsCaching() {
437
    $image_effect_definitions_called = &drupal_static('image_module_test_image_effect_info_alter');
438

    
439
    // First call should grab a fresh copy of the data.
440
    $effects = image_effect_definitions();
441
    $this->assertTrue($image_effect_definitions_called === 1, 'image_effect_definitions() generated data.');
442

    
443
    // Second call should come from cache.
444
    drupal_static_reset('image_effect_definitions');
445
    drupal_static_reset('image_module_test_image_effect_info_alter');
446
    $cached_effects = image_effect_definitions();
447
    $this->assertTrue(is_null($image_effect_definitions_called), 'image_effect_definitions() returned data from cache.');
448

    
449
    $this->assertTrue($effects == $cached_effects, 'Cached effects are the same as generated effects.');
450
  }
451
}
452

    
453
/**
454
 * Tests creation, deletion, and editing of image styles and effects.
455
 */
456
class ImageAdminStylesUnitTest extends ImageFieldTestCase {
457

    
458
  public static function getInfo() {
459
    return array(
460
      'name' => 'Image styles and effects UI configuration',
461
      'description' => 'Tests creation, deletion, and editing of image styles and effects at the UI level.',
462
      'group' => 'Image',
463
    );
464
  }
465

    
466
  /**
467
   * Given an image style, generate an image.
468
   */
469
  function createSampleImage($style) {
470
    static $file_path;
471

    
472
    // First, we need to make sure we have an image in our testing
473
    // file directory. Copy over an image on the first run.
474
    if (!isset($file_path)) {
475
      $files = $this->drupalGetTestFiles('image');
476
      $file = reset($files);
477
      $file_path = file_unmanaged_copy($file->uri);
478
    }
479

    
480
    return image_style_url($style['name'], $file_path) ? $file_path : FALSE;
481
  }
482

    
483
  /**
484
   * Count the number of images currently create for a style.
485
   */
486
  function getImageCount($style) {
487
    return count(file_scan_directory('public://styles/' . $style['name'], '/.*/'));
488
  }
489

    
490
  /**
491
   * Test creating an image style with a numeric name and ensuring it can be
492
   * applied to an image.
493
   */
494
  function testNumericStyleName() {
495
    $style_name = rand();
496
    $style_label = $this->randomString();
497
    $edit = array(
498
      'name' => $style_name,
499
      'label' => $style_label,
500
    );
501
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
502
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
503
    $options = image_style_options();
504
    $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', array('%key' => $style_name)));
505
  }
506

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

    
544
    // Add style form.
545

    
546
    $edit = array(
547
      'name' => $style_name,
548
      'label' => $style_label,
549
    );
550
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
551
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
552

    
553
    // Add effect form.
554

    
555
    // Add each sample effect to the style.
556
    foreach ($effect_edits as $effect => $edit) {
557
      // Add the effect.
558
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
559
      if (!empty($edit)) {
560
        $this->drupalPost(NULL, $edit, t('Add effect'));
561
      }
562
    }
563

    
564
    // Edit effect form.
565

    
566
    // Revisit each form to make sure the effect was saved.
567
    drupal_static_reset('image_styles');
568
    $style = image_style_load($style_name);
569

    
570
    foreach ($style['effects'] as $ieid => $effect) {
571
      $this->drupalGet($style_path . '/effects/' . $ieid);
572
      foreach ($effect_edits[$effect['name']] as $field => $value) {
573
        $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)));
574
      }
575
    }
576

    
577
    // Image style overview form (ordering and renaming).
578

    
579
    // Confirm the order of effects is maintained according to the order we
580
    // added the fields.
581
    $effect_edits_order = array_keys($effect_edits);
582
    $effects_order = array_values($style['effects']);
583
    $order_correct = TRUE;
584
    foreach ($effects_order as $index => $effect) {
585
      if ($effect_edits_order[$index] != $effect['name']) {
586
        $order_correct = FALSE;
587
      }
588
    }
589
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
590

    
591
    // Test the style overview form.
592
    // Change the name of the style and adjust the weights of effects.
593
    $style_name = strtolower($this->randomName(10));
594
    $style_label = $this->randomString();
595
    $weight = count($effect_edits);
596
    $edit = array(
597
      'name' => $style_name,
598
      'label' => $style_label,
599
    );
600
    foreach ($style['effects'] as $ieid => $effect) {
601
      $edit['effects[' . $ieid . '][weight]'] = $weight;
602
      $weight--;
603
    }
604

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

    
609
    $this->drupalPost($style_path, $edit, t('Update style'));
610

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

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

    
618
    // Check that the image was flushed after updating the style.
619
    // This is especially important when renaming the style. Make sure that
620
    // the old image directory has been deleted.
621
    $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'])));
622

    
623
    // Load the style by the new name with the new weights.
624
    drupal_static_reset('image_styles');
625
    $style = image_style_load($style_name, NULL);
626

    
627
    // Confirm the new style order was saved.
628
    $effect_edits_order = array_reverse($effect_edits_order);
629
    $effects_order = array_values($style['effects']);
630
    $order_correct = TRUE;
631
    foreach ($effects_order as $index => $effect) {
632
      if ($effect_edits_order[$index] != $effect['name']) {
633
        $order_correct = FALSE;
634
      }
635
    }
636
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
637

    
638
    // Image effect deletion form.
639

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

    
644
    // Test effect deletion form.
645
    $effect = array_pop($style['effects']);
646
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
647
    $this->assertRaw(t('The image effect %name has been deleted.', array('%name' => $effect['label'])), 'Image effect deleted.');
648

    
649
    // Style deletion form.
650

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

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

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

    
661
  }
662

    
663
  /**
664
   * Test to override, edit, then revert a style.
665
   */
666
  function testDefaultStyle() {
667
    // Setup a style to be created and effects to add to it.
668
    $style_name = 'thumbnail';
669
    $style_label = 'Thumbnail (100x100)';
670
    $edit_path = 'admin/config/media/image-styles/edit/' . $style_name;
671
    $delete_path = 'admin/config/media/image-styles/delete/' . $style_name;
672
    $revert_path = 'admin/config/media/image-styles/revert/' . $style_name;
673

    
674
    // Ensure deleting a default is not possible.
675
    $this->drupalGet($delete_path);
676
    $this->assertText(t('Page not found'), 'Default styles may not be deleted.');
677

    
678
    // Ensure that editing a default is not possible (without overriding).
679
    $this->drupalGet($edit_path);
680
    $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
681
    $this->assertTrue($disabled_field, 'Default styles may not be renamed.');
682
    $this->assertNoField('edit-submit', 'Default styles may not be edited.');
683
    $this->assertNoField('edit-add', 'Default styles may not have new effects added.');
684

    
685
    // Create an image to make sure the default works before overriding.
686
    drupal_static_reset('image_styles');
687
    $style = image_style_load($style_name);
688
    $image_path = $this->createSampleImage($style);
689
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
690

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

    
696
    // Override the default.
697
    $this->drupalPost($edit_path, array(), t('Override defaults'));
698
    $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.');
699

    
700
    // Add sample effect to the overridden style.
701
    $this->drupalPost($edit_path, array('new' => 'image_desaturate'), t('Add'));
702
    drupal_static_reset('image_styles');
703
    $style = image_style_load($style_name);
704

    
705
    // Verify that effects attached to the style have an ieid now.
706
    foreach ($style['effects'] as $effect) {
707
      $this->assertTrue(isset($effect['ieid']), format_string('The %effect effect has an ieid.', array('%effect' => $effect['name'])));
708
    }
709

    
710
    // The style should now have 2 effect, the original scale provided by core
711
    // and the desaturate effect we added in the override.
712
    $effects = array_values($style['effects']);
713
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the overridden style.');
714
    $this->assertEqual($effects[1]['name'], 'image_desaturate', 'The added effect exists in the overridden style.');
715

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

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

    
725
    // Revert the image style.
726
    $this->drupalPost($revert_path, array(), t('Revert'));
727
    drupal_static_reset('image_styles');
728
    $style = image_style_load($style_name);
729

    
730
    // The style should now have the single effect for scale.
731
    $effects = array_values($style['effects']);
732
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the reverted style.');
733
    $this->assertFalse(array_key_exists(1, $effects), 'The added effect has been removed in the reverted style.');
734
  }
735

    
736
  /**
737
   * Test deleting a style and choosing a replacement style.
738
   */
739
  function testStyleReplacement() {
740
    // Create a new style.
741
    $style_name = strtolower($this->randomName(10));
742
    $style_label = $this->randomString();
743
    image_style_save(array('name' => $style_name, 'label' => $style_label));
744
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
745

    
746
    // Create an image field that uses the new style.
747
    $field_name = strtolower($this->randomName(10));
748
    $this->createImageField($field_name, 'article');
749
    $instance = field_info_instance('node', $field_name, 'article');
750
    $instance['display']['default']['type'] = 'image';
751
    $instance['display']['default']['settings']['image_style'] = $style_name;
752
    field_update_instance($instance);
753

    
754
    // Create a new node with an image attached.
755
    $test_image = current($this->drupalGetTestFiles('image'));
756
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
757
    $node = node_load($nid);
758

    
759
    // Test that image is displayed using newly created style.
760
    $this->drupalGet('node/' . $nid);
761
    $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)));
762

    
763
    // Rename the style and make sure the image field is updated.
764
    $new_style_name = strtolower($this->randomName(10));
765
    $new_style_label = $this->randomString();
766
    $edit = array(
767
      'name' => $new_style_name,
768
      'label' => $new_style_label,
769
    );
770
    $this->drupalPost('admin/config/media/image-styles/edit/' . $style_name, $edit, t('Update style'));
771
    $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)));
772
    $this->drupalGet('node/' . $nid);
773
    $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.'));
774

    
775
    // Delete the style and choose a replacement style.
776
    $edit = array(
777
      'replacement' => 'thumbnail',
778
    );
779
    $this->drupalPost('admin/config/media/image-styles/delete/' . $new_style_name, $edit, t('Delete'));
780
    $message = t('Style %name was deleted.', array('%name' => $new_style_label));
781
    $this->assertRaw($message, $message);
782

    
783
    $this->drupalGet('node/' . $nid);
784
    $this->assertRaw(check_plain(image_style_url('thumbnail', $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
785
  }
786
}
787

    
788
/**
789
 * Test class to check that formatters and display settings are working.
790
 */
791
class ImageFieldDisplayTestCase extends ImageFieldTestCase {
792
  public static function getInfo() {
793
    return array(
794
      'name' => 'Image field display tests',
795
      'description' => 'Test the display of image fields.',
796
      'group' => 'Image',
797
    );
798
  }
799

    
800
  /**
801
   * Test image formatters on node display for public files.
802
   */
803
  function testImageFieldFormattersPublic() {
804
    $this->_testImageFieldFormatters('public');
805
  }
806

    
807
  /**
808
   * Test image formatters on node display for private files.
809
   */
810
  function testImageFieldFormattersPrivate() {
811
    // Remove access content permission from anonymous users.
812
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access content' => FALSE));
813
    $this->_testImageFieldFormatters('private');
814
  }
815

    
816
  /**
817
   * Test image formatters on node display.
818
   */
819
  function _testImageFieldFormatters($scheme) {
820
    $field_name = strtolower($this->randomName());
821
    $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme));
822
    // Create a new node with an image attached.
823
    $test_image = current($this->drupalGetTestFiles('image'));
824
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
825
    $node = node_load($nid, NULL, TRUE);
826

    
827
    // Test that the default formatter is being used.
828
    $image_uri = $node->{$field_name}[LANGUAGE_NONE][0]['uri'];
829
    $image_info = array(
830
      'path' => $image_uri,
831
      'width' => 40,
832
      'height' => 20,
833
    );
834
    $default_output = theme('image', $image_info);
835
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
836

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

    
853
      // Log out and try to access the file.
854
      $this->drupalLogout();
855
      $this->drupalGet(file_create_url($image_uri));
856
      $this->assertResponse('403', 'Access denied to original image as anonymous user.');
857

    
858
      // Log in again.
859
      $this->drupalLogin($this->admin_user);
860
    }
861

    
862
    // Test the image linked to content formatter.
863
    $instance['display']['default']['settings']['image_link'] = 'content';
864
    field_update_instance($instance);
865
    $default_output = l(theme('image', $image_info), 'node/' . $nid, array('html' => TRUE, 'attributes' => array('class' => 'active')));
866
    $this->drupalGet('node/' . $nid);
867
    $this->assertRaw($default_output, 'Image linked to content formatter displaying correctly on full node view.');
868

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

    
885
    if ($scheme == 'private') {
886
      // Log out and try to access the file.
887
      $this->drupalLogout();
888
      $this->drupalGet(image_style_url('thumbnail', $image_uri));
889
      $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
890
    }
891
  }
892

    
893
  /**
894
   * Tests for image field settings.
895
   */
896
  function testImageFieldSettings() {
897
    $test_image = current($this->drupalGetTestFiles('image'));
898
    list(, $test_image_extension) = explode('.', $test_image->filename);
899
    $field_name = strtolower($this->randomName());
900
    $instance_settings = array(
901
      'alt_field' => 1,
902
      'file_extensions' => $test_image_extension,
903
      'max_filesize' => '50 KB',
904
      'max_resolution' => '100x100',
905
      'min_resolution' => '10x10',
906
      'title_field' => 1,
907
    );
908
    $widget_settings = array(
909
      'preview_image_style' => 'medium',
910
    );
911
    $field = $this->createImageField($field_name, 'article', array(), $instance_settings, $widget_settings);
912
    $field['deleted'] = 0;
913
    $table = _field_sql_storage_tablename($field);
914
    $schema = drupal_get_schema($table, TRUE);
915
    $instance = field_info_instance('node', $field_name, 'article');
916

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

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

    
939
    // Add alt/title fields to the image and verify that they are displayed.
940
    $image_info = array(
941
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
942
      'alt' => $this->randomName(),
943
      'title' => $this->randomName(),
944
      'width' => 40,
945
      'height' => 20,
946
    );
947
    $edit = array(
948
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $image_info['alt'],
949
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $image_info['title'],
950
    );
951
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
952
    $default_output = theme('image', $image_info);
953
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
954

    
955
    // Verify that alt/title longer than allowed results in a validation error.
956
    $test_size = 2000;
957
    $edit = array(
958
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $this->randomName($test_size),
959
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $this->randomName($test_size),
960
    );
961
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
962
    $this->assertRaw(t('Alternate text cannot be longer than %max characters but is currently %length characters long.', array(
963
      '%max' => $schema['fields'][$field_name .'_alt']['length'],
964
      '%length' => $test_size,
965
    )));
966
    $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
967
      '%max' => $schema['fields'][$field_name .'_title']['length'],
968
      '%length' => $test_size,
969
    )));
970
  }
971

    
972
  /**
973
   * Test passing attributes into the image field formatters.
974
   */
975
  function testImageFieldFormatterAttributes() {
976
    $image = theme('image_formatter', array(
977
      'item' => array(
978
        'uri' => 'http://example.com/example.png',
979
        'attributes' => array(
980
          'data-image-field-formatter' => 'testFound',
981
        ),
982
        'alt' => t('Image field formatter attribute test.'),
983
        'title' => t('Image field formatter'),
984
      ),
985
    ));
986
    $this->assertTrue(stripos($image, 'testFound') > 0, 'Image field formatters can have attributes.');
987
  }
988

    
989
  /**
990
   * Test use of a default image with an image field.
991
   */
992
  function testImageFieldDefaultImage() {
993
    // Create a new image field.
994
    $field_name = strtolower($this->randomName());
995
    $this->createImageField($field_name, 'article');
996

    
997
    // Create a new node, with no images and verify that no images are
998
    // displayed.
999
    $node = $this->drupalCreateNode(array('type' => 'article'));
1000
    $this->drupalGet('node/' . $node->nid);
1001
    // Verify that no image is displayed on the page by checking for the class
1002
    // that would be used on the image field.
1003
    $this->assertNoPattern('<div class="(.*?)field-name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
1004

    
1005
    // Add a default image to the public imagefield instance.
1006
    $images = $this->drupalGetTestFiles('image');
1007
    $edit = array(
1008
      'files[field_settings_default_image]' => drupal_realpath($images[0]->uri),
1009
    );
1010
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
1011
    // Clear field info cache so the new default image is detected.
1012
    field_info_cache_clear();
1013
    $field = field_info_field($field_name);
1014
    $image = file_load($field['settings']['default_image']);
1015
    $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
1016
    $default_output = theme('image', array('path' => $image->uri));
1017
    $this->drupalGet('node/' . $node->nid);
1018
    $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
1019

    
1020
    // Create a node with an image attached and ensure that the default image
1021
    // is not displayed.
1022
    $nid = $this->uploadNodeImage($images[1], $field_name, 'article');
1023
    $node = node_load($nid, NULL, TRUE);
1024
    $image_info = array(
1025
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
1026
      'width' => 40,
1027
      'height' => 20,
1028
    );
1029
    $image_output = theme('image', $image_info);
1030
    $this->drupalGet('node/' . $nid);
1031
    $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
1032
    $this->assertRaw($image_output, 'User supplied image is displayed.');
1033

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

    
1065
/**
1066
 * Test class to check for various validations.
1067
 */
1068
class ImageFieldValidateTestCase extends ImageFieldTestCase {
1069
  public static function getInfo() {
1070
    return array(
1071
      'name' => 'Image field validation tests',
1072
      'description' => 'Tests validation functions such as min/max resolution.',
1073
      'group' => 'Image',
1074
    );
1075
  }
1076

    
1077
  /**
1078
   * Test min/max resolution settings.
1079
   */
1080
  function testResolution() {
1081
    $field_name = strtolower($this->randomName());
1082
    $min_resolution = 50;
1083
    $max_resolution = 100;
1084
    $instance_settings = array(
1085
      'max_resolution' => $max_resolution . 'x' . $max_resolution,
1086
      'min_resolution' => $min_resolution . 'x' . $min_resolution,
1087
    );
1088
    $this->createImageField($field_name, 'article', array(), $instance_settings);
1089

    
1090
    // We want a test image that is too small, and a test image that is too
1091
    // big, so cycle through test image files until we have what we need.
1092
    $image_that_is_too_big = FALSE;
1093
    $image_that_is_too_small = FALSE;
1094
    foreach ($this->drupalGetTestFiles('image') as $image) {
1095
      $info = image_get_info($image->uri);
1096
      if ($info['width'] > $max_resolution) {
1097
        $image_that_is_too_big = $image;
1098
      }
1099
      if ($info['width'] < $min_resolution) {
1100
        $image_that_is_too_small = $image;
1101
      }
1102
      if ($image_that_is_too_small && $image_that_is_too_big) {
1103
        break;
1104
      }
1105
    }
1106
    $nid = $this->uploadNodeImage($image_that_is_too_small, $field_name, 'article');
1107
    $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.');
1108
    $nid = $this->uploadNodeImage($image_that_is_too_big, $field_name, 'article');
1109
    $this->assertText(t('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.'), 'Image exceeding max resolution was properly resized.');
1110
  }
1111
}
1112

    
1113
/**
1114
 * Tests that images have correct dimensions when styled.
1115
 */
1116
class ImageDimensionsTestCase extends DrupalWebTestCase {
1117

    
1118
  public static function getInfo() {
1119
    return array(
1120
      'name' => 'Image dimensions',
1121
      'description' => 'Tests that images have correct dimensions when styled.',
1122
      'group' => 'Image',
1123
    );
1124
  }
1125

    
1126
  function setUp() {
1127
    parent::setUp('image_module_test');
1128
  }
1129

    
1130
  /**
1131
   * Test styled image dimensions cumulatively.
1132
   */
1133
  function testImageDimensions() {
1134
    // Create a working copy of the file.
1135
    $files = $this->drupalGetTestFiles('image');
1136
    $file = reset($files);
1137
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1138

    
1139
    // Create a style.
1140
    $style = image_style_save(array('name' => 'test', 'label' => 'Test'));
1141
    $generated_uri = 'public://styles/test/public/'. drupal_basename($original_uri);
1142
    $url = image_style_url('test', $original_uri);
1143

    
1144
    $variables = array(
1145
      'style_name' => 'test',
1146
      'path' => $original_uri,
1147
      'width' => 40,
1148
      'height' => 20,
1149
    );
1150

    
1151
    // Scale an image that is wider than it is high.
1152
    $effect = array(
1153
      'name' => 'image_scale',
1154
      'data' => array(
1155
        'width' => 120,
1156
        'height' => 90,
1157
        'upscale' => TRUE,
1158
      ),
1159
      'isid' => $style['isid'],
1160
    );
1161

    
1162
    image_effect_save($effect);
1163
    $img_tag = theme_image_style($variables);
1164
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="120" height="60" alt="" />', 'Expected img tag was found.');
1165
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1166
    $this->drupalGet($url);
1167
    $this->assertResponse(200, 'Image was generated at the URL.');
1168
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1169
    $image_info = image_get_info($generated_uri);
1170
    $this->assertEqual($image_info['width'], 120, 'Expected width was found.');
1171
    $this->assertEqual($image_info['height'], 60, 'Expected height was found.');
1172

    
1173
    // Rotate 90 degrees anticlockwise.
1174
    $effect = array(
1175
      'name' => 'image_rotate',
1176
      'data' => array(
1177
        'degrees' => -90,
1178
        'random' => FALSE,
1179
      ),
1180
      'isid' => $style['isid'],
1181
    );
1182

    
1183
    image_effect_save($effect);
1184
    $img_tag = theme_image_style($variables);
1185
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="60" height="120" alt="" />', 'Expected img tag was found.');
1186
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1187
    $this->drupalGet($url);
1188
    $this->assertResponse(200, 'Image was generated at the URL.');
1189
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1190
    $image_info = image_get_info($generated_uri);
1191
    $this->assertEqual($image_info['width'], 60, 'Expected width was found.');
1192
    $this->assertEqual($image_info['height'], 120, 'Expected height was found.');
1193

    
1194
    // Scale an image that is higher than it is wide (rotated by previous effect).
1195
    $effect = array(
1196
      'name' => 'image_scale',
1197
      'data' => array(
1198
        'width' => 120,
1199
        'height' => 90,
1200
        'upscale' => TRUE,
1201
      ),
1202
      'isid' => $style['isid'],
1203
    );
1204

    
1205
    image_effect_save($effect);
1206
    $img_tag = theme_image_style($variables);
1207
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1208
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1209
    $this->drupalGet($url);
1210
    $this->assertResponse(200, 'Image was generated at the URL.');
1211
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1212
    $image_info = image_get_info($generated_uri);
1213
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1214
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1215

    
1216
    // Test upscale disabled.
1217
    $effect = array(
1218
      'name' => 'image_scale',
1219
      'data' => array(
1220
        'width' => 400,
1221
        'height' => 200,
1222
        'upscale' => FALSE,
1223
      ),
1224
      'isid' => $style['isid'],
1225
    );
1226

    
1227
    image_effect_save($effect);
1228
    $img_tag = theme_image_style($variables);
1229
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1230
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1231
    $this->drupalGet($url);
1232
    $this->assertResponse(200, 'Image was generated at the URL.');
1233
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1234
    $image_info = image_get_info($generated_uri);
1235
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1236
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1237

    
1238
    // Add a desaturate effect.
1239
    $effect = array(
1240
      'name' => 'image_desaturate',
1241
      'data' => array(),
1242
      'isid' => $style['isid'],
1243
    );
1244

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

    
1256
    // Add a random rotate effect.
1257
    $effect = array(
1258
      'name' => 'image_rotate',
1259
      'data' => array(
1260
        'degrees' => 180,
1261
        'random' => TRUE,
1262
      ),
1263
      'isid' => $style['isid'],
1264
    );
1265

    
1266
    image_effect_save($effect);
1267
    $img_tag = theme_image_style($variables);
1268
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1269
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1270
    $this->drupalGet($url);
1271
    $this->assertResponse(200, 'Image was generated at the URL.');
1272
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1273

    
1274

    
1275
    // Add a crop effect.
1276
    $effect = array(
1277
      'name' => 'image_crop',
1278
      'data' => array(
1279
        'width' => 30,
1280
        'height' => 30,
1281
        'anchor' => 'center-center',
1282
      ),
1283
      'isid' => $style['isid'],
1284
    );
1285

    
1286
    image_effect_save($effect);
1287
    $img_tag = theme_image_style($variables);
1288
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="30" height="30" alt="" />', 'Expected img tag was found.');
1289
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1290
    $this->drupalGet($url);
1291
    $this->assertResponse(200, 'Image was generated at the URL.');
1292
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1293
    $image_info = image_get_info($generated_uri);
1294
    $this->assertEqual($image_info['width'], 30, 'Expected width was found.');
1295
    $this->assertEqual($image_info['height'], 30, 'Expected height was found.');
1296

    
1297
    // Rotate to a non-multiple of 90 degrees.
1298
    $effect = array(
1299
      'name' => 'image_rotate',
1300
      'data' => array(
1301
        'degrees' => 57,
1302
        'random' => FALSE,
1303
      ),
1304
      'isid' => $style['isid'],
1305
    );
1306

    
1307
    $effect = image_effect_save($effect);
1308
    $img_tag = theme_image_style($variables);
1309
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1310
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1311
    $this->drupalGet($url);
1312
    $this->assertResponse(200, 'Image was generated at the URL.');
1313
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1314

    
1315
    image_effect_delete($effect);
1316

    
1317
    // Ensure that an effect with no dimensions callback unsets the dimensions.
1318
    // This ensures compatibility with 7.0 contrib modules.
1319
    $effect = array(
1320
      'name' => 'image_module_test_null',
1321
      'data' => array(),
1322
      'isid' => $style['isid'],
1323
    );
1324

    
1325
    image_effect_save($effect);
1326
    $img_tag = theme_image_style($variables);
1327
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1328
  }
1329
}
1330

    
1331
/**
1332
 * Tests image_dimensions_scale().
1333
 */
1334
class ImageDimensionsScaleTestCase extends DrupalUnitTestCase {
1335
  public static function getInfo() {
1336
    return array(
1337
      'name' => 'image_dimensions_scale()',
1338
      'description' => 'Tests all control flow branches in image_dimensions_scale().',
1339
      'group' => 'Image',
1340
    );
1341
  }
1342

    
1343
  /**
1344
   * Tests all control flow branches in image_dimensions_scale().
1345
   */
1346
  function testImageDimensionsScale() {
1347
    // Define input / output datasets to test different branch conditions.
1348
    $test = array();
1349

    
1350
    // Test branch conditions:
1351
    // - No height.
1352
    // - Upscale, don't need to upscale.
1353
    $tests[] = array(
1354
      'input' => array(
1355
        'dimensions' => array(
1356
          'width' => 1000,
1357
          'height' => 2000,
1358
        ),
1359
        'width' => 200,
1360
        'height' => NULL,
1361
        'upscale' => TRUE,
1362
      ),
1363
      'output' => array(
1364
        'dimensions' => array(
1365
          'width' => 200,
1366
          'height' => 400,
1367
        ),
1368
        'return_value' => TRUE,
1369
      ),
1370
    );
1371

    
1372
    // Test branch conditions:
1373
    // - No width.
1374
    // - Don't upscale, don't need to upscale.
1375
    $tests[] = array(
1376
      'input' => array(
1377
        'dimensions' => array(
1378
          'width' => 1000,
1379
          'height' => 800,
1380
        ),
1381
        'width' => NULL,
1382
        'height' => 140,
1383
        'upscale' => FALSE,
1384
      ),
1385
      'output' => array(
1386
        'dimensions' => array(
1387
          'width' => 175,
1388
          'height' => 140,
1389
        ),
1390
        'return_value' => TRUE,
1391
      ),
1392
    );
1393

    
1394
    // Test branch conditions:
1395
    // - Source aspect ratio greater than target.
1396
    // - Upscale, need to upscale.
1397
    $tests[] = array(
1398
      'input' => array(
1399
        'dimensions' => array(
1400
          'width' => 8,
1401
          'height' => 20,
1402
        ),
1403
        'width' => 200,
1404
        'height' => 140,
1405
        'upscale' => TRUE,
1406
      ),
1407
      'output' => array(
1408
        'dimensions' => array(
1409
          'width' => 56,
1410
          'height' => 140,
1411
        ),
1412
        'return_value' => TRUE,
1413
      ),
1414
    );
1415

    
1416
    // Test branch condition: target aspect ratio greater than source.
1417
    $tests[] = array(
1418
      'input' => array(
1419
        'dimensions' => array(
1420
          'width' => 2000,
1421
          'height' => 800,
1422
        ),
1423
        'width' => 200,
1424
        'height' => 140,
1425
        'upscale' => FALSE,
1426
      ),
1427
      'output' => array(
1428
        'dimensions' => array(
1429
          'width' => 200,
1430
          'height' => 80,
1431
        ),
1432
        'return_value' => TRUE,
1433
      ),
1434
    );
1435

    
1436
    // Test branch condition: don't upscale, need to upscale.
1437
    $tests[] = array(
1438
      'input' => array(
1439
        'dimensions' => array(
1440
          'width' => 100,
1441
          'height' => 50,
1442
        ),
1443
        'width' => 200,
1444
        'height' => 140,
1445
        'upscale' => FALSE,
1446
      ),
1447
      'output' => array(
1448
        'dimensions' => array(
1449
          'width' => 100,
1450
          'height' => 50,
1451
        ),
1452
        'return_value' => FALSE,
1453
      ),
1454
    );
1455

    
1456
    foreach ($tests as $test) {
1457
      // Process the test dataset.
1458
      $return_value = image_dimensions_scale($test['input']['dimensions'], $test['input']['width'], $test['input']['height'], $test['input']['upscale']);
1459

    
1460
      // Check the width.
1461
      $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'])));
1462

    
1463
      // Check the height.
1464
      $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'])));
1465

    
1466
      // Check the return value.
1467
      $this->assertEqual($test['output']['return_value'], $return_value, 'Correct return value.');
1468
    }
1469
  }
1470
}
1471

    
1472
/**
1473
 * Tests default image settings.
1474
 */
1475
class ImageFieldDefaultImagesTestCase extends ImageFieldTestCase {
1476

    
1477
  public static function getInfo() {
1478
    return array(
1479
      'name' => 'Image field default images tests',
1480
      'description' => 'Tests setting up default images both to the field and field instance.',
1481
      'group' => 'Image',
1482
    );
1483
  }
1484

    
1485
  function setUp() {
1486
    parent::setUp(array('field_ui'));
1487
  }
1488

    
1489
  /**
1490
   * Tests CRUD for fields and fields instances with default images.
1491
   */
1492
  function testDefaultImages() {
1493
    // Create files to use as the default images.
1494
    $files = $this->drupalGetTestFiles('image');
1495
    $default_images = array();
1496
    foreach (array('field', 'instance', 'instance2', 'field_new', 'instance_new') as $image_target) {
1497
      $file = array_pop($files);
1498
      $file = file_save($file);
1499
      $default_images[$image_target] = $file;
1500
    }
1501

    
1502
    // Create an image field and add an instance to the article content type.
1503
    $field_name = strtolower($this->randomName());
1504
    $field_settings = array(
1505
      'default_image' => $default_images['field']->fid,
1506
    );
1507
    $instance_settings = array(
1508
      'default_image' => $default_images['instance']->fid,
1509
    );
1510
    $widget_settings = array(
1511
      'preview_image_style' => 'medium',
1512
    );
1513
    $this->createImageField($field_name, 'article', $field_settings, $instance_settings, $widget_settings);
1514
    $field = field_info_field($field_name);
1515
    $instance = field_info_instance('node', $field_name, 'article');
1516

    
1517
    // Add another instance with another default image to the page content type.
1518
    $instance2 = array_merge($instance, array(
1519
      'bundle' => 'page',
1520
      'settings' => array(
1521
        'default_image' => $default_images['instance2']->fid,
1522
      ),
1523
    ));
1524
    field_create_instance($instance2);
1525
    $instance2 = field_info_instance('node', $field_name, 'page');
1526

    
1527

    
1528
    // Confirm the defaults are present on the article field admin form.
1529
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1530
    $this->assertFieldByXpath(
1531
      '//input[@name="field[settings][default_image][fid]"]',
1532
      $default_images['field']->fid,
1533
      format_string(
1534
        'Article image field default equals expected file ID of @fid.',
1535
        array('@fid' => $default_images['field']->fid)
1536
      )
1537
    );
1538
    $this->assertFieldByXpath(
1539
      '//input[@name="instance[settings][default_image][fid]"]',
1540
      $default_images['instance']->fid,
1541
      format_string(
1542
        'Article image field instance default equals expected file ID of @fid.',
1543
        array('@fid' => $default_images['instance']->fid)
1544
      )
1545
    );
1546

    
1547
    // Confirm the defaults are present on the page field admin form.
1548
    $this->drupalGet("admin/structure/types/manage/page/fields/$field_name");
1549
    $this->assertFieldByXpath(
1550
      '//input[@name="field[settings][default_image][fid]"]',
1551
      $default_images['field']->fid,
1552
      format_string(
1553
        'Page image field default equals expected file ID of @fid.',
1554
        array('@fid' => $default_images['field']->fid)
1555
      )
1556
    );
1557
    $this->assertFieldByXpath(
1558
      '//input[@name="instance[settings][default_image][fid]"]',
1559
      $default_images['instance2']->fid,
1560
      format_string(
1561
        'Page image field instance default equals expected file ID of @fid.',
1562
        array('@fid' => $default_images['instance2']->fid)
1563
      )
1564
    );
1565

    
1566
    // Confirm that the image default is shown for a new article node.
1567
    $article = $this->drupalCreateNode(array('type' => 'article'));
1568
    $article_built = node_view($article);
1569
    $this->assertEqual(
1570
      $article_built[$field_name]['#items'][0]['fid'],
1571
      $default_images['instance']->fid,
1572
      format_string(
1573
        'A new article node without an image has the expected default image file ID of @fid.',
1574
        array('@fid' => $default_images['instance']->fid)
1575
      )
1576
    );
1577

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

    
1590
    // Upload a new default for the field.
1591
    $field['settings']['default_image'] = $default_images['field_new']->fid;
1592
    field_update_field($field);
1593

    
1594
    // Confirm that the new field default is used on the article admin form.
1595
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1596
    $this->assertFieldByXpath(
1597
      '//input[@name="field[settings][default_image][fid]"]',
1598
      $default_images['field_new']->fid,
1599
      format_string(
1600
        'Updated image field default equals expected file ID of @fid.',
1601
        array('@fid' => $default_images['field_new']->fid)
1602
      )
1603
    );
1604

    
1605
    // Reload the nodes and confirm the field instance defaults are used.
1606
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1607
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1608
    $this->assertEqual(
1609
      $article_built[$field_name]['#items'][0]['fid'],
1610
      $default_images['instance']->fid,
1611
      format_string(
1612
        'An existing article node without an image has the expected default image file ID of @fid.',
1613
        array('@fid' => $default_images['instance']->fid)
1614
      )
1615
    );
1616
    $this->assertEqual(
1617
      $page_built[$field_name]['#items'][0]['fid'],
1618
      $default_images['instance2']->fid,
1619
      format_string(
1620
        'An existing page node without an image has the expected default image file ID of @fid.',
1621
        array('@fid' => $default_images['instance2']->fid)
1622
      )
1623
    );
1624

    
1625
    // Upload a new default for the article's field instance.
1626
    $instance['settings']['default_image'] = $default_images['instance_new']->fid;
1627
    field_update_instance($instance);
1628

    
1629
    // Confirm the new field instance default is used on the article field
1630
    // admin form.
1631
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1632
    $this->assertFieldByXpath(
1633
      '//input[@name="instance[settings][default_image][fid]"]',
1634
      $default_images['instance_new']->fid,
1635
      format_string(
1636
        'Updated article image field instance default equals expected file ID of @fid.',
1637
        array('@fid' => $default_images['instance_new']->fid)
1638
      )
1639
    );
1640

    
1641
    // Reload the nodes.
1642
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1643
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1644

    
1645
    // Confirm the article uses the new default.
1646
    $this->assertEqual(
1647
      $article_built[$field_name]['#items'][0]['fid'],
1648
      $default_images['instance_new']->fid,
1649
      format_string(
1650
        'An existing article node without an image has the expected default image file ID of @fid.',
1651
        array('@fid' => $default_images['instance_new']->fid)
1652
      )
1653
    );
1654
    // Confirm the page remains unchanged.
1655
    $this->assertEqual(
1656
      $page_built[$field_name]['#items'][0]['fid'],
1657
      $default_images['instance2']->fid,
1658
      format_string(
1659
        'An existing page node without an image has the expected default image file ID of @fid.',
1660
        array('@fid' => $default_images['instance2']->fid)
1661
      )
1662
    );
1663

    
1664
    // Remove the instance default from articles.
1665
    $instance['settings']['default_image'] = NULL;
1666
    field_update_instance($instance);
1667

    
1668
    // Confirm the article field instance default has been removed.
1669
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1670
    $this->assertFieldByXpath(
1671
      '//input[@name="instance[settings][default_image][fid]"]',
1672
      '',
1673
      'Updated article image field instance default has been successfully removed.'
1674
    );
1675

    
1676
    // Reload the nodes.
1677
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1678
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1679
    // Confirm the article uses the new field (not instance) default.
1680
    $this->assertEqual(
1681
      $article_built[$field_name]['#items'][0]['fid'],
1682
      $default_images['field_new']->fid,
1683
      format_string(
1684
        'An existing article node without an image has the expected default image file ID of @fid.',
1685
        array('@fid' => $default_images['field_new']->fid)
1686
      )
1687
    );
1688
    // Confirm the page remains unchanged.
1689
    $this->assertEqual(
1690
      $page_built[$field_name]['#items'][0]['fid'],
1691
      $default_images['instance2']->fid,
1692
      format_string(
1693
        'An existing page node without an image has the expected default image file ID of @fid.',
1694
        array('@fid' => $default_images['instance2']->fid)
1695
      )
1696
    );
1697
  }
1698

    
1699
}
1700

    
1701
/**
1702
 * Tests image theme functions.
1703
 */
1704
class ImageThemeFunctionWebTestCase extends DrupalWebTestCase {
1705

    
1706
  public static function getInfo() {
1707
    return array(
1708
      'name' => 'Image theme functions',
1709
      'description' => 'Test that the image theme functions work correctly.',
1710
      'group' => 'Image',
1711
    );
1712
  }
1713

    
1714
  function setUp() {
1715
    parent::setUp(array('image'));
1716
  }
1717

    
1718
  /**
1719
   * Tests usage of the image field formatters.
1720
   */
1721
  function testImageFormatterTheme() {
1722
    // Create an image.
1723
    $files = $this->drupalGetTestFiles('image');
1724
    $file = reset($files);
1725
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1726

    
1727
    // Create a style.
1728
    image_style_save(array('name' => 'test', 'label' => 'Test'));
1729
    $url = image_style_url('test', $original_uri);
1730

    
1731
    // Test using theme_image_formatter() without an image title, alt text, or
1732
    // link options.
1733
    $path = $this->randomName();
1734
    $element = array(
1735
      '#theme' => 'image_formatter',
1736
      '#image_style' => 'test',
1737
      '#item' => array(
1738
        'uri' => $original_uri,
1739
      ),
1740
      '#path' => array(
1741
        'path' => $path,
1742
      ),
1743
    );
1744
    $rendered_element = render($element);
1745
    $expected_result = '<a href="' . url($path) . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1746
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders without title, alt, or path options.');
1747

    
1748
    // Link the image to a fragment on the page, and not a full URL.
1749
    $fragment = $this->randomName();
1750
    $element['#path']['path'] = '';
1751
    $element['#path']['options'] = array(
1752
      'external' => TRUE,
1753
      'fragment' => $fragment,
1754
    );
1755
    $rendered_element = render($element);
1756
    $expected_result = '<a href="#' . $fragment . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1757
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders a link fragment.');
1758
  }
1759

    
1760
}
1761

    
1762
/**
1763
 * Tests flushing of image styles.
1764
 */
1765
class ImageStyleFlushTest extends ImageFieldTestCase {
1766

    
1767
  public static function getInfo() {
1768
    return array(
1769
      'name' => 'Image style flushing',
1770
      'description' => 'Tests flushing of image styles.',
1771
      'group' => 'Image',
1772
    );
1773
  }
1774

    
1775
  /**
1776
   * Given an image style and a wrapper, generate an image.
1777
   */
1778
  function createSampleImage($style, $wrapper) {
1779
    static $file;
1780

    
1781
    if (!isset($file)) {
1782
      $files = $this->drupalGetTestFiles('image');
1783
      $file = reset($files);
1784
    }
1785

    
1786
    // Make sure we have an image in our wrapper testing file directory.
1787
    $source_uri = file_unmanaged_copy($file->uri, $wrapper . '://');
1788
    // Build the derivative image.
1789
    $derivative_uri = image_style_path($style['name'], $source_uri);
1790
    $derivative = image_style_create_derivative($style, $source_uri, $derivative_uri);
1791

    
1792
    return $derivative ? $derivative_uri : FALSE;
1793
  }
1794

    
1795
  /**
1796
   * Count the number of images currently created for a style in a wrapper.
1797
   */
1798
  function getImageCount($style, $wrapper) {
1799
    return count(file_scan_directory($wrapper . '://styles/' . $style['name'], '/.*/'));
1800
  }
1801

    
1802
  /**
1803
   * General test to flush a style.
1804
   */
1805
  function testFlush() {
1806

    
1807
    // Setup a style to be created and effects to add to it.
1808
    $style_name = strtolower($this->randomName(10));
1809
    $style_label = $this->randomString();
1810
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
1811
    $effect_edits = array(
1812
      'image_resize' => array(
1813
        'data[width]' => 100,
1814
        'data[height]' => 101,
1815
      ),
1816
      'image_scale' => array(
1817
        'data[width]' => 110,
1818
        'data[height]' => 111,
1819
        'data[upscale]' => 1,
1820
      ),
1821
    );
1822

    
1823
    // Add style form.
1824
    $edit = array(
1825
      'name' => $style_name,
1826
      'label' => $style_label,
1827
    );
1828
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
1829
    // Add each sample effect to the style.
1830
    foreach ($effect_edits as $effect => $edit) {
1831
      // Add the effect.
1832
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
1833
      if (!empty($edit)) {
1834
        $this->drupalPost(NULL, $edit, t('Add effect'));
1835
      }
1836
    }
1837

    
1838
    // Load the saved image style.
1839
    $style = image_style_load($style_name);
1840

    
1841
    // Create an image for the 'public' wrapper.
1842
    $image_path = $this->createSampleImage($style, 'public');
1843
    // Expecting to find 2 images, one is the sample.png image shown in
1844
    // image style preview.
1845
    $this->assertEqual($this->getImageCount($style, 'public'), 2, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
1846

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

    
1851
    // Remove the 'image_scale' effect and updates the style, which in turn
1852
    // forces an image style flush.
1853
    $effect = array_pop($style['effects']);
1854
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
1855
    $this->assertResponse(200);
1856
    $this->drupalPost($style_path, array(), t('Update style'));
1857
    $this->assertResponse(200);
1858

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

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