Projet

Général

Profil

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

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

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
    // Suppress the security token in the URL, then get the URL of a file. Check
334
    // that the security token is not present in the URL but that the image is
335
    // still accessible.
336
    variable_set('image_suppress_itok_output', TRUE);
337
    $generate_url = image_style_url($this->style_name, $original_uri);
338
    $this->assertIdentical(strpos($generate_url, IMAGE_DERIVATIVE_TOKEN . '='), FALSE, 'The security token does not appear in the image style URL.');
339
    $this->drupalGet($generate_url);
340
    $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
341

    
342
    // Check that requesting a nonexistent image does not create any new
343
    // directories in the file system.
344
    $directory = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/' . $this->randomName();
345
    $this->drupalGet(file_create_url($directory . '/' . $this->randomName()));
346
    $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
347
  }
348
}
349

    
350
/**
351
 * Use the image_test.module's mock toolkit to ensure that the effects are
352
 * properly passing parameters to the image toolkit.
353
 */
354
class ImageEffectsUnitTest extends ImageToolkitTestCase {
355
  public static function getInfo() {
356
    return array(
357
      'name' => 'Image effects',
358
      'description' => 'Test that the image effects pass parameters to the toolkit correctly.',
359
      'group' => 'Image',
360
    );
361
  }
362

    
363
  function setUp() {
364
    parent::setUp('image_module_test');
365
    module_load_include('inc', 'image', 'image.effects');
366
  }
367

    
368
  /**
369
   * Test the image_resize_effect() function.
370
   */
371
  function testResizeEffect() {
372
    $this->assertTrue(image_resize_effect($this->image, array('width' => 1, 'height' => 2)), 'Function returned the expected value.');
373
    $this->assertToolkitOperationsCalled(array('resize'));
374

    
375
    // Check the parameters.
376
    $calls = image_test_get_all_calls();
377
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
378
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
379
  }
380

    
381
  /**
382
   * Test the image_scale_effect() function.
383
   */
384
  function testScaleEffect() {
385
    // @todo: need to test upscaling.
386
    $this->assertTrue(image_scale_effect($this->image, array('width' => 10, 'height' => 10)), 'Function returned the expected value.');
387
    $this->assertToolkitOperationsCalled(array('resize'));
388

    
389
    // Check the parameters.
390
    $calls = image_test_get_all_calls();
391
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
392
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
393
  }
394

    
395
  /**
396
   * Test the image_crop_effect() function.
397
   */
398
  function testCropEffect() {
399
    // @todo should test the keyword offsets.
400
    $this->assertTrue(image_crop_effect($this->image, array('anchor' => 'top-1', 'width' => 3, 'height' => 4)), 'Function returned the expected value.');
401
    $this->assertToolkitOperationsCalled(array('crop'));
402

    
403
    // Check the parameters.
404
    $calls = image_test_get_all_calls();
405
    $this->assertEqual($calls['crop'][0][1], 0, 'X was passed correctly');
406
    $this->assertEqual($calls['crop'][0][2], 1, 'Y was passed correctly');
407
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
408
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
409
  }
410

    
411
  /**
412
   * Test the image_scale_and_crop_effect() function.
413
   */
414
  function testScaleAndCropEffect() {
415
    $this->assertTrue(image_scale_and_crop_effect($this->image, array('width' => 5, 'height' => 10)), 'Function returned the expected value.');
416
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));
417

    
418
    // Check the parameters.
419
    $calls = image_test_get_all_calls();
420
    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
421
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
422
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
423
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
424
  }
425

    
426
  /**
427
   * Test the image_desaturate_effect() function.
428
   */
429
  function testDesaturateEffect() {
430
    $this->assertTrue(image_desaturate_effect($this->image, array()), 'Function returned the expected value.');
431
    $this->assertToolkitOperationsCalled(array('desaturate'));
432

    
433
    // Check the parameters.
434
    $calls = image_test_get_all_calls();
435
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
436
  }
437

    
438
  /**
439
   * Test the image_rotate_effect() function.
440
   */
441
  function testRotateEffect() {
442
    // @todo: need to test with 'random' => TRUE
443
    $this->assertTrue(image_rotate_effect($this->image, array('degrees' => 90, 'bgcolor' => '#fff')), 'Function returned the expected value.');
444
    $this->assertToolkitOperationsCalled(array('rotate'));
445

    
446
    // Check the parameters.
447
    $calls = image_test_get_all_calls();
448
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
449
    $this->assertEqual($calls['rotate'][0][2], 0xffffff, 'Background color was passed correctly');
450
  }
451

    
452
  /**
453
   * Test image effect caching.
454
   */
455
  function testImageEffectsCaching() {
456
    $image_effect_definitions_called = &drupal_static('image_module_test_image_effect_info_alter');
457

    
458
    // First call should grab a fresh copy of the data.
459
    $effects = image_effect_definitions();
460
    $this->assertTrue($image_effect_definitions_called === 1, 'image_effect_definitions() generated data.');
461

    
462
    // Second call should come from cache.
463
    drupal_static_reset('image_effect_definitions');
464
    drupal_static_reset('image_module_test_image_effect_info_alter');
465
    $cached_effects = image_effect_definitions();
466
    $this->assertTrue(is_null($image_effect_definitions_called), 'image_effect_definitions() returned data from cache.');
467

    
468
    $this->assertTrue($effects == $cached_effects, 'Cached effects are the same as generated effects.');
469
  }
470
}
471

    
472
/**
473
 * Tests creation, deletion, and editing of image styles and effects.
474
 */
475
class ImageAdminStylesUnitTest extends ImageFieldTestCase {
476

    
477
  public static function getInfo() {
478
    return array(
479
      'name' => 'Image styles and effects UI configuration',
480
      'description' => 'Tests creation, deletion, and editing of image styles and effects at the UI level.',
481
      'group' => 'Image',
482
    );
483
  }
484

    
485
  /**
486
   * Given an image style, generate an image.
487
   */
488
  function createSampleImage($style) {
489
    static $file_path;
490

    
491
    // First, we need to make sure we have an image in our testing
492
    // file directory. Copy over an image on the first run.
493
    if (!isset($file_path)) {
494
      $files = $this->drupalGetTestFiles('image');
495
      $file = reset($files);
496
      $file_path = file_unmanaged_copy($file->uri);
497
    }
498

    
499
    return image_style_url($style['name'], $file_path) ? $file_path : FALSE;
500
  }
501

    
502
  /**
503
   * Count the number of images currently create for a style.
504
   */
505
  function getImageCount($style) {
506
    return count(file_scan_directory('public://styles/' . $style['name'], '/.*/'));
507
  }
508

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

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

    
563
    // Add style form.
564

    
565
    $edit = array(
566
      'name' => $style_name,
567
      'label' => $style_label,
568
    );
569
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
570
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
571

    
572
    // Add effect form.
573

    
574
    // Add each sample effect to the style.
575
    foreach ($effect_edits as $effect => $edit) {
576
      // Add the effect.
577
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
578
      if (!empty($edit)) {
579
        $this->drupalPost(NULL, $edit, t('Add effect'));
580
      }
581
    }
582

    
583
    // Edit effect form.
584

    
585
    // Revisit each form to make sure the effect was saved.
586
    drupal_static_reset('image_styles');
587
    $style = image_style_load($style_name);
588

    
589
    foreach ($style['effects'] as $ieid => $effect) {
590
      $this->drupalGet($style_path . '/effects/' . $ieid);
591
      foreach ($effect_edits[$effect['name']] as $field => $value) {
592
        $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)));
593
      }
594
    }
595

    
596
    // Image style overview form (ordering and renaming).
597

    
598
    // Confirm the order of effects is maintained according to the order we
599
    // added the fields.
600
    $effect_edits_order = array_keys($effect_edits);
601
    $effects_order = array_values($style['effects']);
602
    $order_correct = TRUE;
603
    foreach ($effects_order as $index => $effect) {
604
      if ($effect_edits_order[$index] != $effect['name']) {
605
        $order_correct = FALSE;
606
      }
607
    }
608
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
609

    
610
    // Test the style overview form.
611
    // Change the name of the style and adjust the weights of effects.
612
    $style_name = strtolower($this->randomName(10));
613
    $style_label = $this->randomString();
614
    $weight = count($effect_edits);
615
    $edit = array(
616
      'name' => $style_name,
617
      'label' => $style_label,
618
    );
619
    foreach ($style['effects'] as $ieid => $effect) {
620
      $edit['effects[' . $ieid . '][weight]'] = $weight;
621
      $weight--;
622
    }
623

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

    
628
    $this->drupalPost($style_path, $edit, t('Update style'));
629

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

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

    
637
    // Check that the image was flushed after updating the style.
638
    // This is especially important when renaming the style. Make sure that
639
    // the old image directory has been deleted.
640
    $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'])));
641

    
642
    // Load the style by the new name with the new weights.
643
    drupal_static_reset('image_styles');
644
    $style = image_style_load($style_name, NULL);
645

    
646
    // Confirm the new style order was saved.
647
    $effect_edits_order = array_reverse($effect_edits_order);
648
    $effects_order = array_values($style['effects']);
649
    $order_correct = TRUE;
650
    foreach ($effects_order as $index => $effect) {
651
      if ($effect_edits_order[$index] != $effect['name']) {
652
        $order_correct = FALSE;
653
      }
654
    }
655
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
656

    
657
    // Image effect deletion form.
658

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

    
663
    // Test effect deletion form.
664
    $effect = array_pop($style['effects']);
665
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
666
    $this->assertRaw(t('The image effect %name has been deleted.', array('%name' => $effect['label'])), 'Image effect deleted.');
667

    
668
    // Style deletion form.
669

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

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

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

    
680
  }
681

    
682
  /**
683
   * Test to override, edit, then revert a style.
684
   */
685
  function testDefaultStyle() {
686
    // Setup a style to be created and effects to add to it.
687
    $style_name = 'thumbnail';
688
    $style_label = 'Thumbnail (100x100)';
689
    $edit_path = 'admin/config/media/image-styles/edit/' . $style_name;
690
    $delete_path = 'admin/config/media/image-styles/delete/' . $style_name;
691
    $revert_path = 'admin/config/media/image-styles/revert/' . $style_name;
692

    
693
    // Ensure deleting a default is not possible.
694
    $this->drupalGet($delete_path);
695
    $this->assertText(t('Page not found'), 'Default styles may not be deleted.');
696

    
697
    // Ensure that editing a default is not possible (without overriding).
698
    $this->drupalGet($edit_path);
699
    $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
700
    $this->assertTrue($disabled_field, 'Default styles may not be renamed.');
701
    $this->assertNoField('edit-submit', 'Default styles may not be edited.');
702
    $this->assertNoField('edit-add', 'Default styles may not have new effects added.');
703

    
704
    // Create an image to make sure the default works before overriding.
705
    drupal_static_reset('image_styles');
706
    $style = image_style_load($style_name);
707
    $image_path = $this->createSampleImage($style);
708
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
709

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

    
715
    // Override the default.
716
    $this->drupalPost($edit_path, array(), t('Override defaults'));
717
    $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.');
718

    
719
    // Add sample effect to the overridden style.
720
    $this->drupalPost($edit_path, array('new' => 'image_desaturate'), t('Add'));
721
    drupal_static_reset('image_styles');
722
    $style = image_style_load($style_name);
723

    
724
    // Verify that effects attached to the style have an ieid now.
725
    foreach ($style['effects'] as $effect) {
726
      $this->assertTrue(isset($effect['ieid']), format_string('The %effect effect has an ieid.', array('%effect' => $effect['name'])));
727
    }
728

    
729
    // The style should now have 2 effect, the original scale provided by core
730
    // and the desaturate effect we added in the override.
731
    $effects = array_values($style['effects']);
732
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the overridden style.');
733
    $this->assertEqual($effects[1]['name'], 'image_desaturate', 'The added effect exists in the overridden style.');
734

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

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

    
744
    // Revert the image style.
745
    $this->drupalPost($revert_path, array(), t('Revert'));
746
    drupal_static_reset('image_styles');
747
    $style = image_style_load($style_name);
748

    
749
    // The style should now have the single effect for scale.
750
    $effects = array_values($style['effects']);
751
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the reverted style.');
752
    $this->assertFalse(array_key_exists(1, $effects), 'The added effect has been removed in the reverted style.');
753
  }
754

    
755
  /**
756
   * Test deleting a style and choosing a replacement style.
757
   */
758
  function testStyleReplacement() {
759
    // Create a new style.
760
    $style_name = strtolower($this->randomName(10));
761
    $style_label = $this->randomString();
762
    image_style_save(array('name' => $style_name, 'label' => $style_label));
763
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
764

    
765
    // Create an image field that uses the new style.
766
    $field_name = strtolower($this->randomName(10));
767
    $this->createImageField($field_name, 'article');
768
    $instance = field_info_instance('node', $field_name, 'article');
769
    $instance['display']['default']['type'] = 'image';
770
    $instance['display']['default']['settings']['image_style'] = $style_name;
771
    field_update_instance($instance);
772

    
773
    // Create a new node with an image attached.
774
    $test_image = current($this->drupalGetTestFiles('image'));
775
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
776
    $node = node_load($nid);
777

    
778
    // Test that image is displayed using newly created style.
779
    $this->drupalGet('node/' . $nid);
780
    $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)));
781

    
782
    // Rename the style and make sure the image field is updated.
783
    $new_style_name = strtolower($this->randomName(10));
784
    $new_style_label = $this->randomString();
785
    $edit = array(
786
      'name' => $new_style_name,
787
      'label' => $new_style_label,
788
    );
789
    $this->drupalPost('admin/config/media/image-styles/edit/' . $style_name, $edit, t('Update style'));
790
    $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)));
791
    $this->drupalGet('node/' . $nid);
792
    $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.'));
793

    
794
    // Delete the style and choose a replacement style.
795
    $edit = array(
796
      'replacement' => 'thumbnail',
797
    );
798
    $this->drupalPost('admin/config/media/image-styles/delete/' . $new_style_name, $edit, t('Delete'));
799
    $message = t('Style %name was deleted.', array('%name' => $new_style_label));
800
    $this->assertRaw($message, $message);
801

    
802
    $this->drupalGet('node/' . $nid);
803
    $this->assertRaw(check_plain(image_style_url('thumbnail', $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
804
  }
805
}
806

    
807
/**
808
 * Test class to check that formatters and display settings are working.
809
 */
810
class ImageFieldDisplayTestCase extends ImageFieldTestCase {
811
  public static function getInfo() {
812
    return array(
813
      'name' => 'Image field display tests',
814
      'description' => 'Test the display of image fields.',
815
      'group' => 'Image',
816
    );
817
  }
818

    
819
  /**
820
   * Test image formatters on node display for public files.
821
   */
822
  function testImageFieldFormattersPublic() {
823
    $this->_testImageFieldFormatters('public');
824
  }
825

    
826
  /**
827
   * Test image formatters on node display for private files.
828
   */
829
  function testImageFieldFormattersPrivate() {
830
    // Remove access content permission from anonymous users.
831
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access content' => FALSE));
832
    $this->_testImageFieldFormatters('private');
833
  }
834

    
835
  /**
836
   * Test image formatters on node display.
837
   */
838
  function _testImageFieldFormatters($scheme) {
839
    $field_name = strtolower($this->randomName());
840
    $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme));
841
    // Create a new node with an image attached.
842
    $test_image = current($this->drupalGetTestFiles('image'));
843
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
844
    $node = node_load($nid, NULL, TRUE);
845

    
846
    // Test that the default formatter is being used.
847
    $image_uri = $node->{$field_name}[LANGUAGE_NONE][0]['uri'];
848
    $image_info = array(
849
      'path' => $image_uri,
850
      'width' => 40,
851
      'height' => 20,
852
    );
853
    $default_output = theme('image', $image_info);
854
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
855

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

    
872
      // Log out and try to access the file.
873
      $this->drupalLogout();
874
      $this->drupalGet(file_create_url($image_uri));
875
      $this->assertResponse('403', 'Access denied to original image as anonymous user.');
876

    
877
      // Log in again.
878
      $this->drupalLogin($this->admin_user);
879
    }
880

    
881
    // Test the image linked to content formatter.
882
    $instance['display']['default']['settings']['image_link'] = 'content';
883
    field_update_instance($instance);
884
    $default_output = l(theme('image', $image_info), 'node/' . $nid, array('html' => TRUE, 'attributes' => array('class' => 'active')));
885
    $this->drupalGet('node/' . $nid);
886
    $this->assertRaw($default_output, 'Image linked to content formatter displaying correctly on full node view.');
887

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

    
904
    if ($scheme == 'private') {
905
      // Log out and try to access the file.
906
      $this->drupalLogout();
907
      $this->drupalGet(image_style_url('thumbnail', $image_uri));
908
      $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
909
    }
910
  }
911

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

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

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

    
958
    // Add alt/title fields to the image and verify that they are displayed.
959
    $image_info = array(
960
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
961
      'alt' => $this->randomName(),
962
      'title' => $this->randomName(),
963
      'width' => 40,
964
      'height' => 20,
965
    );
966
    $edit = array(
967
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $image_info['alt'],
968
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $image_info['title'],
969
    );
970
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
971
    $default_output = theme('image', $image_info);
972
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
973

    
974
    // Verify that alt/title longer than allowed results in a validation error.
975
    $test_size = 2000;
976
    $edit = array(
977
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $this->randomName($test_size),
978
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $this->randomName($test_size),
979
    );
980
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
981
    $this->assertRaw(t('Alternate text cannot be longer than %max characters but is currently %length characters long.', array(
982
      '%max' => $schema['fields'][$field_name .'_alt']['length'],
983
      '%length' => $test_size,
984
    )));
985
    $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
986
      '%max' => $schema['fields'][$field_name .'_title']['length'],
987
      '%length' => $test_size,
988
    )));
989
  }
990

    
991
  /**
992
   * Test passing attributes into the image field formatters.
993
   */
994
  function testImageFieldFormatterAttributes() {
995
    $image = theme('image_formatter', array(
996
      'item' => array(
997
        'uri' => 'http://example.com/example.png',
998
        'attributes' => array(
999
          'data-image-field-formatter' => 'testFound',
1000
        ),
1001
        'alt' => t('Image field formatter attribute test.'),
1002
        'title' => t('Image field formatter'),
1003
      ),
1004
    ));
1005
    $this->assertTrue(stripos($image, 'testFound') > 0, 'Image field formatters can have attributes.');
1006
  }
1007

    
1008
  /**
1009
   * Test use of a default image with an image field.
1010
   */
1011
  function testImageFieldDefaultImage() {
1012
    // Create a new image field.
1013
    $field_name = strtolower($this->randomName());
1014
    $this->createImageField($field_name, 'article');
1015

    
1016
    // Create a new node, with no images and verify that no images are
1017
    // displayed.
1018
    $node = $this->drupalCreateNode(array('type' => 'article'));
1019
    $this->drupalGet('node/' . $node->nid);
1020
    // Verify that no image is displayed on the page by checking for the class
1021
    // that would be used on the image field.
1022
    $this->assertNoPattern('<div class="(.*?)field-name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
1023

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

    
1039
    // Create a node with an image attached and ensure that the default image
1040
    // is not displayed.
1041
    $nid = $this->uploadNodeImage($images[1], $field_name, 'article');
1042
    $node = node_load($nid, NULL, TRUE);
1043
    $image_info = array(
1044
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
1045
      'width' => 40,
1046
      'height' => 20,
1047
    );
1048
    $image_output = theme('image', $image_info);
1049
    $this->drupalGet('node/' . $nid);
1050
    $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
1051
    $this->assertRaw($image_output, 'User supplied image is displayed.');
1052

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

    
1084
/**
1085
 * Test class to check for various validations.
1086
 */
1087
class ImageFieldValidateTestCase extends ImageFieldTestCase {
1088
  public static function getInfo() {
1089
    return array(
1090
      'name' => 'Image field validation tests',
1091
      'description' => 'Tests validation functions such as min/max resolution.',
1092
      'group' => 'Image',
1093
    );
1094
  }
1095

    
1096
  /**
1097
   * Test min/max resolution settings.
1098
   */
1099
  function testResolution() {
1100
    $field_name = strtolower($this->randomName());
1101
    $min_resolution = 50;
1102
    $max_resolution = 100;
1103
    $instance_settings = array(
1104
      'max_resolution' => $max_resolution . 'x' . $max_resolution,
1105
      'min_resolution' => $min_resolution . 'x' . $min_resolution,
1106
    );
1107
    $this->createImageField($field_name, 'article', array(), $instance_settings);
1108

    
1109
    // We want a test image that is too small, and a test image that is too
1110
    // big, so cycle through test image files until we have what we need.
1111
    $image_that_is_too_big = FALSE;
1112
    $image_that_is_too_small = FALSE;
1113
    foreach ($this->drupalGetTestFiles('image') as $image) {
1114
      $info = image_get_info($image->uri);
1115
      if ($info['width'] > $max_resolution) {
1116
        $image_that_is_too_big = $image;
1117
      }
1118
      if ($info['width'] < $min_resolution) {
1119
        $image_that_is_too_small = $image;
1120
      }
1121
      if ($image_that_is_too_small && $image_that_is_too_big) {
1122
        break;
1123
      }
1124
    }
1125
    $nid = $this->uploadNodeImage($image_that_is_too_small, $field_name, 'article');
1126
    $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.');
1127
    $nid = $this->uploadNodeImage($image_that_is_too_big, $field_name, 'article');
1128
    $this->assertText(t('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.'), 'Image exceeding max resolution was properly resized.');
1129
  }
1130
}
1131

    
1132
/**
1133
 * Tests that images have correct dimensions when styled.
1134
 */
1135
class ImageDimensionsTestCase extends DrupalWebTestCase {
1136

    
1137
  public static function getInfo() {
1138
    return array(
1139
      'name' => 'Image dimensions',
1140
      'description' => 'Tests that images have correct dimensions when styled.',
1141
      'group' => 'Image',
1142
    );
1143
  }
1144

    
1145
  function setUp() {
1146
    parent::setUp('image_module_test');
1147
  }
1148

    
1149
  /**
1150
   * Test styled image dimensions cumulatively.
1151
   */
1152
  function testImageDimensions() {
1153
    // Create a working copy of the file.
1154
    $files = $this->drupalGetTestFiles('image');
1155
    $file = reset($files);
1156
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1157

    
1158
    // Create a style.
1159
    $style = image_style_save(array('name' => 'test', 'label' => 'Test'));
1160
    $generated_uri = 'public://styles/test/public/'. drupal_basename($original_uri);
1161
    $url = image_style_url('test', $original_uri);
1162

    
1163
    $variables = array(
1164
      'style_name' => 'test',
1165
      'path' => $original_uri,
1166
      'width' => 40,
1167
      'height' => 20,
1168
    );
1169

    
1170
    // Scale an image that is wider than it is high.
1171
    $effect = array(
1172
      'name' => 'image_scale',
1173
      'data' => array(
1174
        'width' => 120,
1175
        'height' => 90,
1176
        'upscale' => TRUE,
1177
      ),
1178
      'isid' => $style['isid'],
1179
    );
1180

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

    
1192
    // Rotate 90 degrees anticlockwise.
1193
    $effect = array(
1194
      'name' => 'image_rotate',
1195
      'data' => array(
1196
        'degrees' => -90,
1197
        'random' => FALSE,
1198
      ),
1199
      'isid' => $style['isid'],
1200
    );
1201

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

    
1213
    // Scale an image that is higher than it is wide (rotated by previous effect).
1214
    $effect = array(
1215
      'name' => 'image_scale',
1216
      'data' => array(
1217
        'width' => 120,
1218
        'height' => 90,
1219
        'upscale' => TRUE,
1220
      ),
1221
      'isid' => $style['isid'],
1222
    );
1223

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

    
1235
    // Test upscale disabled.
1236
    $effect = array(
1237
      'name' => 'image_scale',
1238
      'data' => array(
1239
        'width' => 400,
1240
        'height' => 200,
1241
        'upscale' => FALSE,
1242
      ),
1243
      'isid' => $style['isid'],
1244
    );
1245

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

    
1257
    // Add a desaturate effect.
1258
    $effect = array(
1259
      'name' => 'image_desaturate',
1260
      'data' => array(),
1261
      'isid' => $style['isid'],
1262
    );
1263

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

    
1275
    // Add a random rotate effect.
1276
    $effect = array(
1277
      'name' => 'image_rotate',
1278
      'data' => array(
1279
        'degrees' => 180,
1280
        'random' => TRUE,
1281
      ),
1282
      'isid' => $style['isid'],
1283
    );
1284

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

    
1293

    
1294
    // Add a crop effect.
1295
    $effect = array(
1296
      'name' => 'image_crop',
1297
      'data' => array(
1298
        'width' => 30,
1299
        'height' => 30,
1300
        'anchor' => 'center-center',
1301
      ),
1302
      'isid' => $style['isid'],
1303
    );
1304

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

    
1316
    // Rotate to a non-multiple of 90 degrees.
1317
    $effect = array(
1318
      'name' => 'image_rotate',
1319
      'data' => array(
1320
        'degrees' => 57,
1321
        'random' => FALSE,
1322
      ),
1323
      'isid' => $style['isid'],
1324
    );
1325

    
1326
    $effect = image_effect_save($effect);
1327
    $img_tag = theme_image_style($variables);
1328
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1329
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1330
    $this->drupalGet($url);
1331
    $this->assertResponse(200, 'Image was generated at the URL.');
1332
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1333

    
1334
    image_effect_delete($effect);
1335

    
1336
    // Ensure that an effect with no dimensions callback unsets the dimensions.
1337
    // This ensures compatibility with 7.0 contrib modules.
1338
    $effect = array(
1339
      'name' => 'image_module_test_null',
1340
      'data' => array(),
1341
      'isid' => $style['isid'],
1342
    );
1343

    
1344
    image_effect_save($effect);
1345
    $img_tag = theme_image_style($variables);
1346
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1347
  }
1348
}
1349

    
1350
/**
1351
 * Tests image_dimensions_scale().
1352
 */
1353
class ImageDimensionsScaleTestCase extends DrupalUnitTestCase {
1354
  public static function getInfo() {
1355
    return array(
1356
      'name' => 'image_dimensions_scale()',
1357
      'description' => 'Tests all control flow branches in image_dimensions_scale().',
1358
      'group' => 'Image',
1359
    );
1360
  }
1361

    
1362
  /**
1363
   * Tests all control flow branches in image_dimensions_scale().
1364
   */
1365
  function testImageDimensionsScale() {
1366
    // Define input / output datasets to test different branch conditions.
1367
    $test = array();
1368

    
1369
    // Test branch conditions:
1370
    // - No height.
1371
    // - Upscale, don't need to upscale.
1372
    $tests[] = array(
1373
      'input' => array(
1374
        'dimensions' => array(
1375
          'width' => 1000,
1376
          'height' => 2000,
1377
        ),
1378
        'width' => 200,
1379
        'height' => NULL,
1380
        'upscale' => TRUE,
1381
      ),
1382
      'output' => array(
1383
        'dimensions' => array(
1384
          'width' => 200,
1385
          'height' => 400,
1386
        ),
1387
        'return_value' => TRUE,
1388
      ),
1389
    );
1390

    
1391
    // Test branch conditions:
1392
    // - No width.
1393
    // - Don't upscale, don't need to upscale.
1394
    $tests[] = array(
1395
      'input' => array(
1396
        'dimensions' => array(
1397
          'width' => 1000,
1398
          'height' => 800,
1399
        ),
1400
        'width' => NULL,
1401
        'height' => 140,
1402
        'upscale' => FALSE,
1403
      ),
1404
      'output' => array(
1405
        'dimensions' => array(
1406
          'width' => 175,
1407
          'height' => 140,
1408
        ),
1409
        'return_value' => TRUE,
1410
      ),
1411
    );
1412

    
1413
    // Test branch conditions:
1414
    // - Source aspect ratio greater than target.
1415
    // - Upscale, need to upscale.
1416
    $tests[] = array(
1417
      'input' => array(
1418
        'dimensions' => array(
1419
          'width' => 8,
1420
          'height' => 20,
1421
        ),
1422
        'width' => 200,
1423
        'height' => 140,
1424
        'upscale' => TRUE,
1425
      ),
1426
      'output' => array(
1427
        'dimensions' => array(
1428
          'width' => 56,
1429
          'height' => 140,
1430
        ),
1431
        'return_value' => TRUE,
1432
      ),
1433
    );
1434

    
1435
    // Test branch condition: target aspect ratio greater than source.
1436
    $tests[] = array(
1437
      'input' => array(
1438
        'dimensions' => array(
1439
          'width' => 2000,
1440
          'height' => 800,
1441
        ),
1442
        'width' => 200,
1443
        'height' => 140,
1444
        'upscale' => FALSE,
1445
      ),
1446
      'output' => array(
1447
        'dimensions' => array(
1448
          'width' => 200,
1449
          'height' => 80,
1450
        ),
1451
        'return_value' => TRUE,
1452
      ),
1453
    );
1454

    
1455
    // Test branch condition: don't upscale, need to upscale.
1456
    $tests[] = array(
1457
      'input' => array(
1458
        'dimensions' => array(
1459
          'width' => 100,
1460
          'height' => 50,
1461
        ),
1462
        'width' => 200,
1463
        'height' => 140,
1464
        'upscale' => FALSE,
1465
      ),
1466
      'output' => array(
1467
        'dimensions' => array(
1468
          'width' => 100,
1469
          'height' => 50,
1470
        ),
1471
        'return_value' => FALSE,
1472
      ),
1473
    );
1474

    
1475
    foreach ($tests as $test) {
1476
      // Process the test dataset.
1477
      $return_value = image_dimensions_scale($test['input']['dimensions'], $test['input']['width'], $test['input']['height'], $test['input']['upscale']);
1478

    
1479
      // Check the width.
1480
      $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'])));
1481

    
1482
      // Check the height.
1483
      $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'])));
1484

    
1485
      // Check the return value.
1486
      $this->assertEqual($test['output']['return_value'], $return_value, 'Correct return value.');
1487
    }
1488
  }
1489
}
1490

    
1491
/**
1492
 * Tests default image settings.
1493
 */
1494
class ImageFieldDefaultImagesTestCase extends ImageFieldTestCase {
1495

    
1496
  public static function getInfo() {
1497
    return array(
1498
      'name' => 'Image field default images tests',
1499
      'description' => 'Tests setting up default images both to the field and field instance.',
1500
      'group' => 'Image',
1501
    );
1502
  }
1503

    
1504
  function setUp() {
1505
    parent::setUp(array('field_ui'));
1506
  }
1507

    
1508
  /**
1509
   * Tests CRUD for fields and fields instances with default images.
1510
   */
1511
  function testDefaultImages() {
1512
    // Create files to use as the default images.
1513
    $files = $this->drupalGetTestFiles('image');
1514
    $default_images = array();
1515
    foreach (array('field', 'instance', 'instance2', 'field_new', 'instance_new') as $image_target) {
1516
      $file = array_pop($files);
1517
      $file = file_save($file);
1518
      $default_images[$image_target] = $file;
1519
    }
1520

    
1521
    // Create an image field and add an instance to the article content type.
1522
    $field_name = strtolower($this->randomName());
1523
    $field_settings = array(
1524
      'default_image' => $default_images['field']->fid,
1525
    );
1526
    $instance_settings = array(
1527
      'default_image' => $default_images['instance']->fid,
1528
    );
1529
    $widget_settings = array(
1530
      'preview_image_style' => 'medium',
1531
    );
1532
    $this->createImageField($field_name, 'article', $field_settings, $instance_settings, $widget_settings);
1533
    $field = field_info_field($field_name);
1534
    $instance = field_info_instance('node', $field_name, 'article');
1535

    
1536
    // Add another instance with another default image to the page content type.
1537
    $instance2 = array_merge($instance, array(
1538
      'bundle' => 'page',
1539
      'settings' => array(
1540
        'default_image' => $default_images['instance2']->fid,
1541
      ),
1542
    ));
1543
    field_create_instance($instance2);
1544
    $instance2 = field_info_instance('node', $field_name, 'page');
1545

    
1546

    
1547
    // Confirm the defaults are present on the article field admin form.
1548
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1549
    $this->assertFieldByXpath(
1550
      '//input[@name="field[settings][default_image][fid]"]',
1551
      $default_images['field']->fid,
1552
      format_string(
1553
        'Article 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['instance']->fid,
1560
      format_string(
1561
        'Article image field instance default equals expected file ID of @fid.',
1562
        array('@fid' => $default_images['instance']->fid)
1563
      )
1564
    );
1565

    
1566
    // Confirm the defaults are present on the page field admin form.
1567
    $this->drupalGet("admin/structure/types/manage/page/fields/$field_name");
1568
    $this->assertFieldByXpath(
1569
      '//input[@name="field[settings][default_image][fid]"]',
1570
      $default_images['field']->fid,
1571
      format_string(
1572
        'Page image field default equals expected file ID of @fid.',
1573
        array('@fid' => $default_images['field']->fid)
1574
      )
1575
    );
1576
    $this->assertFieldByXpath(
1577
      '//input[@name="instance[settings][default_image][fid]"]',
1578
      $default_images['instance2']->fid,
1579
      format_string(
1580
        'Page image field instance default equals expected file ID of @fid.',
1581
        array('@fid' => $default_images['instance2']->fid)
1582
      )
1583
    );
1584

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

    
1597
    // Confirm that the image default is shown for a new page node.
1598
    $page = $this->drupalCreateNode(array('type' => 'page'));
1599
    $page_built = node_view($page);
1600
    $this->assertEqual(
1601
      $page_built[$field_name]['#items'][0]['fid'],
1602
      $default_images['instance2']->fid,
1603
      format_string(
1604
        'A new page node without an image has the expected default image file ID of @fid.',
1605
        array('@fid' => $default_images['instance2']->fid)
1606
      )
1607
    );
1608

    
1609
    // Upload a new default for the field.
1610
    $field['settings']['default_image'] = $default_images['field_new']->fid;
1611
    field_update_field($field);
1612

    
1613
    // Confirm that the new field default is used on the article admin form.
1614
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1615
    $this->assertFieldByXpath(
1616
      '//input[@name="field[settings][default_image][fid]"]',
1617
      $default_images['field_new']->fid,
1618
      format_string(
1619
        'Updated image field default equals expected file ID of @fid.',
1620
        array('@fid' => $default_images['field_new']->fid)
1621
      )
1622
    );
1623

    
1624
    // Reload the nodes and confirm the field instance defaults are used.
1625
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1626
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1627
    $this->assertEqual(
1628
      $article_built[$field_name]['#items'][0]['fid'],
1629
      $default_images['instance']->fid,
1630
      format_string(
1631
        'An existing article node without an image has the expected default image file ID of @fid.',
1632
        array('@fid' => $default_images['instance']->fid)
1633
      )
1634
    );
1635
    $this->assertEqual(
1636
      $page_built[$field_name]['#items'][0]['fid'],
1637
      $default_images['instance2']->fid,
1638
      format_string(
1639
        'An existing page node without an image has the expected default image file ID of @fid.',
1640
        array('@fid' => $default_images['instance2']->fid)
1641
      )
1642
    );
1643

    
1644
    // Upload a new default for the article's field instance.
1645
    $instance['settings']['default_image'] = $default_images['instance_new']->fid;
1646
    field_update_instance($instance);
1647

    
1648
    // Confirm the new field instance default is used on the article field
1649
    // admin form.
1650
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1651
    $this->assertFieldByXpath(
1652
      '//input[@name="instance[settings][default_image][fid]"]',
1653
      $default_images['instance_new']->fid,
1654
      format_string(
1655
        'Updated article image field instance default equals expected file ID of @fid.',
1656
        array('@fid' => $default_images['instance_new']->fid)
1657
      )
1658
    );
1659

    
1660
    // Reload the nodes.
1661
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1662
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1663

    
1664
    // Confirm the article uses the new default.
1665
    $this->assertEqual(
1666
      $article_built[$field_name]['#items'][0]['fid'],
1667
      $default_images['instance_new']->fid,
1668
      format_string(
1669
        'An existing article node without an image has the expected default image file ID of @fid.',
1670
        array('@fid' => $default_images['instance_new']->fid)
1671
      )
1672
    );
1673
    // Confirm the page remains unchanged.
1674
    $this->assertEqual(
1675
      $page_built[$field_name]['#items'][0]['fid'],
1676
      $default_images['instance2']->fid,
1677
      format_string(
1678
        'An existing page node without an image has the expected default image file ID of @fid.',
1679
        array('@fid' => $default_images['instance2']->fid)
1680
      )
1681
    );
1682

    
1683
    // Remove the instance default from articles.
1684
    $instance['settings']['default_image'] = NULL;
1685
    field_update_instance($instance);
1686

    
1687
    // Confirm the article field instance default has been removed.
1688
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1689
    $this->assertFieldByXpath(
1690
      '//input[@name="instance[settings][default_image][fid]"]',
1691
      '',
1692
      'Updated article image field instance default has been successfully removed.'
1693
    );
1694

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

    
1718
}
1719

    
1720
/**
1721
 * Tests image theme functions.
1722
 */
1723
class ImageThemeFunctionWebTestCase extends DrupalWebTestCase {
1724

    
1725
  public static function getInfo() {
1726
    return array(
1727
      'name' => 'Image theme functions',
1728
      'description' => 'Test that the image theme functions work correctly.',
1729
      'group' => 'Image',
1730
    );
1731
  }
1732

    
1733
  function setUp() {
1734
    parent::setUp(array('image'));
1735
  }
1736

    
1737
  /**
1738
   * Tests usage of the image field formatters.
1739
   */
1740
  function testImageFormatterTheme() {
1741
    // Create an image.
1742
    $files = $this->drupalGetTestFiles('image');
1743
    $file = reset($files);
1744
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1745

    
1746
    // Create a style.
1747
    image_style_save(array('name' => 'test', 'label' => 'Test'));
1748
    $url = image_style_url('test', $original_uri);
1749

    
1750
    // Test using theme_image_formatter() without an image title, alt text, or
1751
    // link options.
1752
    $path = $this->randomName();
1753
    $element = array(
1754
      '#theme' => 'image_formatter',
1755
      '#image_style' => 'test',
1756
      '#item' => array(
1757
        'uri' => $original_uri,
1758
      ),
1759
      '#path' => array(
1760
        'path' => $path,
1761
      ),
1762
    );
1763
    $rendered_element = render($element);
1764
    $expected_result = '<a href="' . url($path) . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1765
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders without title, alt, or path options.');
1766

    
1767
    // Link the image to a fragment on the page, and not a full URL.
1768
    $fragment = $this->randomName();
1769
    $element['#path']['path'] = '';
1770
    $element['#path']['options'] = array(
1771
      'external' => TRUE,
1772
      'fragment' => $fragment,
1773
    );
1774
    $rendered_element = render($element);
1775
    $expected_result = '<a href="#' . $fragment . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1776
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders a link fragment.');
1777
  }
1778

    
1779
}
1780

    
1781
/**
1782
 * Tests flushing of image styles.
1783
 */
1784
class ImageStyleFlushTest extends ImageFieldTestCase {
1785

    
1786
  public static function getInfo() {
1787
    return array(
1788
      'name' => 'Image style flushing',
1789
      'description' => 'Tests flushing of image styles.',
1790
      'group' => 'Image',
1791
    );
1792
  }
1793

    
1794
  /**
1795
   * Given an image style and a wrapper, generate an image.
1796
   */
1797
  function createSampleImage($style, $wrapper) {
1798
    static $file;
1799

    
1800
    if (!isset($file)) {
1801
      $files = $this->drupalGetTestFiles('image');
1802
      $file = reset($files);
1803
    }
1804

    
1805
    // Make sure we have an image in our wrapper testing file directory.
1806
    $source_uri = file_unmanaged_copy($file->uri, $wrapper . '://');
1807
    // Build the derivative image.
1808
    $derivative_uri = image_style_path($style['name'], $source_uri);
1809
    $derivative = image_style_create_derivative($style, $source_uri, $derivative_uri);
1810

    
1811
    return $derivative ? $derivative_uri : FALSE;
1812
  }
1813

    
1814
  /**
1815
   * Count the number of images currently created for a style in a wrapper.
1816
   */
1817
  function getImageCount($style, $wrapper) {
1818
    return count(file_scan_directory($wrapper . '://styles/' . $style['name'], '/.*/'));
1819
  }
1820

    
1821
  /**
1822
   * General test to flush a style.
1823
   */
1824
  function testFlush() {
1825

    
1826
    // Setup a style to be created and effects to add to it.
1827
    $style_name = strtolower($this->randomName(10));
1828
    $style_label = $this->randomString();
1829
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
1830
    $effect_edits = array(
1831
      'image_resize' => array(
1832
        'data[width]' => 100,
1833
        'data[height]' => 101,
1834
      ),
1835
      'image_scale' => array(
1836
        'data[width]' => 110,
1837
        'data[height]' => 111,
1838
        'data[upscale]' => 1,
1839
      ),
1840
    );
1841

    
1842
    // Add style form.
1843
    $edit = array(
1844
      'name' => $style_name,
1845
      'label' => $style_label,
1846
    );
1847
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
1848
    // Add each sample effect to the style.
1849
    foreach ($effect_edits as $effect => $edit) {
1850
      // Add the effect.
1851
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
1852
      if (!empty($edit)) {
1853
        $this->drupalPost(NULL, $edit, t('Add effect'));
1854
      }
1855
    }
1856

    
1857
    // Load the saved image style.
1858
    $style = image_style_load($style_name);
1859

    
1860
    // Create an image for the 'public' wrapper.
1861
    $image_path = $this->createSampleImage($style, 'public');
1862
    // Expecting to find 2 images, one is the sample.png image shown in
1863
    // image style preview.
1864
    $this->assertEqual($this->getImageCount($style, 'public'), 2, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
1865

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

    
1870
    // Remove the 'image_scale' effect and updates the style, which in turn
1871
    // forces an image style flush.
1872
    $effect = array_pop($style['effects']);
1873
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
1874
    $this->assertResponse(200);
1875
    $this->drupalPost($style_path, array(), t('Update style'));
1876
    $this->assertResponse(200);
1877

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

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