Projet

Général

Profil

Paste
Télécharger (79,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / image / image.test @ 582db59d

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
   * Create a random style.
82
   *
83
   * @return array
84
   *  A list containing the details of the generated image style.
85
   */
86
  function createRandomStyle() {
87
    $style_name = strtolower($this->randomName(10));
88
    $style_label = $this->randomString();
89
    image_style_save(array('name' => $style_name, 'label' => $style_label));
90
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
91
    return array(
92
      'name' => $style_name,
93
      'label' => $style_label,
94
      'path' => $style_path,
95
    );
96
  }
97

    
98
  /**
99
   * Upload an image to a node.
100
   *
101
   * @param $image
102
   *   A file object representing the image to upload.
103
   * @param $field_name
104
   *   Name of the image field the image should be attached to.
105
   * @param $type
106
   *   The type of node to create.
107
   */
108
  function uploadNodeImage($image, $field_name, $type) {
109
    $edit = array(
110
      'title' => $this->randomName(),
111
    );
112
    $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = drupal_realpath($image->uri);
113
    $this->drupalPost('node/add/' . $type, $edit, t('Save'));
114

    
115
    // Retrieve ID of the newly created node from the current URL.
116
    $matches = array();
117
    preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
118
    return isset($matches[1]) ? $matches[1] : FALSE;
119
  }
120
}
121

    
122
/**
123
 * Tests the functions for generating paths and URLs for image styles.
124
 */
125
class ImageStylesPathAndUrlTestCase extends DrupalWebTestCase {
126
  protected $style_name;
127
  protected $image_info;
128
  protected $image_filepath;
129

    
130
  public static function getInfo() {
131
    return array(
132
      'name' => 'Image styles path and URL functions',
133
      'description' => 'Tests functions for generating paths and URLs to image styles.',
134
      'group' => 'Image',
135
    );
136
  }
137

    
138
  function setUp() {
139
    parent::setUp('image_module_test');
140

    
141
    $this->style_name = 'style_foo';
142
    image_style_save(array('name' => $this->style_name, 'label' => $this->randomString()));
143
  }
144

    
145
  /**
146
   * Test image_style_path().
147
   */
148
  function testImageStylePath() {
149
    $scheme = 'public';
150
    $actual = image_style_path($this->style_name, "$scheme://foo/bar.gif");
151
    $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
152
    $this->assertEqual($actual, $expected, 'Got the path for a file URI.');
153

    
154
    $actual = image_style_path($this->style_name, 'foo/bar.gif');
155
    $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
156
    $this->assertEqual($actual, $expected, 'Got the path for a relative file path.');
157
  }
158

    
159
  /**
160
   * Test image_style_url() with a file using the "public://" scheme.
161
   */
162
  function testImageStyleUrlAndPathPublic() {
163
    $this->_testImageStyleUrlAndPath('public');
164
  }
165

    
166
  /**
167
   * Test image_style_url() with a file using the "private://" scheme.
168
   */
169
  function testImageStyleUrlAndPathPrivate() {
170
    $this->_testImageStyleUrlAndPath('private');
171
  }
172

    
173
  /**
174
   * Test image_style_url() with the "public://" scheme and unclean URLs.
175
   */
176
   function testImageStylUrlAndPathPublicUnclean() {
177
     $this->_testImageStyleUrlAndPath('public', FALSE);
178
   }
179

    
180
  /**
181
   * Test image_style_url() with the "private://" schema and unclean URLs.
182
   */
183
  function testImageStyleUrlAndPathPrivateUnclean() {
184
    $this->_testImageStyleUrlAndPath('private', FALSE);
185
  }
186

    
187
  /**
188
   * Test image_style_url() with a file URL that has an extra slash in it.
189
   */
190
  function testImageStyleUrlExtraSlash() {
191
    $this->_testImageStyleUrlAndPath('public', TRUE, TRUE);
192
  }
193

    
194
  /**
195
   * Test that an invalid source image returns a 404.
196
   */
197
  function testImageStyleUrlForMissingSourceImage() {
198
    $non_existent_uri = 'public://foo.png';
199
    $generated_url = image_style_url($this->style_name, $non_existent_uri);
200
    $this->drupalGet($generated_url);
201
    $this->assertResponse(404, 'Accessing an image style URL with a source image that does not exist provides a 404 error response.');
202
  }
203

    
204
  /**
205
   * Test image_style_url().
206
   */
207
  function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FALSE) {
208
    // Make the default scheme neither "public" nor "private" to verify the
209
    // functions work for other than the default scheme.
210
    variable_set('file_default_scheme', 'temporary');
211
    variable_set('clean_url', $clean_url);
212

    
213
    // Create the directories for the styles.
214
    $directory = $scheme . '://styles/' . $this->style_name;
215
    $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
216
    $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
217

    
218
    // Create a working copy of the file.
219
    $files = $this->drupalGetTestFiles('image');
220
    $file = array_shift($files);
221
    $image_info = image_get_info($file->uri);
222
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
223
    // Let the image_module_test module know about this file, so it can claim
224
    // ownership in hook_file_download().
225
    variable_set('image_module_test_file_download', $original_uri);
226
    $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
227

    
228
    // Get the URL of a file that has not been generated and try to create it.
229
    $generated_uri = image_style_path($this->style_name, $original_uri);
230
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
231
    $generate_url = image_style_url($this->style_name, $original_uri);
232

    
233
    // Ensure that the tests still pass when the file is generated by accessing
234
    // a poorly constructed (but still valid) file URL that has an extra slash
235
    // in it.
236
    if ($extra_slash) {
237
      $modified_uri = str_replace('://', ':///', $original_uri);
238
      $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
239
      $generate_url = image_style_url($this->style_name, $modified_uri);
240
    }
241

    
242
    if (!$clean_url) {
243
      $this->assertTrue(strpos($generate_url, '?q=') !== FALSE, 'When using non-clean URLS, the system path contains the query string.');
244
    }
245
    // Add some extra chars to the token.
246
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
247
    $this->assertResponse(403, 'Image was inaccessible at the URL with an invalid token.');
248
    // Change the parameter name so the token is missing.
249
    $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
250
    $this->assertResponse(403, 'Image was inaccessible at the URL with a missing token.');
251

    
252
    // Check that the generated URL is the same when we pass in a relative path
253
    // rather than a URI. We need to temporarily switch the default scheme to
254
    // match the desired scheme before testing this, then switch it back to the
255
    // "temporary" scheme used throughout this test afterwards.
256
    variable_set('file_default_scheme', $scheme);
257
    $relative_path = file_uri_target($original_uri);
258
    $generate_url_from_relative_path = image_style_url($this->style_name, $relative_path);
259
    $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.');
260
    variable_set('file_default_scheme', 'temporary');
261

    
262
    // Fetch the URL that generates the file.
263
    $this->drupalGet($generate_url);
264
    $this->assertResponse(200, 'Image was generated at the URL.');
265
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
266
    $this->assertRaw(file_get_contents($generated_uri), 'URL returns expected file.');
267
    $generated_image_info = image_get_info($generated_uri);
268
    $this->assertEqual($this->drupalGetHeader('Content-Type'), $generated_image_info['mime_type'], 'Expected Content-Type was reported.');
269
    $this->assertEqual($this->drupalGetHeader('Content-Length'), $generated_image_info['file_size'], 'Expected Content-Length was reported.');
270
    if ($scheme == 'private') {
271
      $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
272
      $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate, post-check=0, pre-check=0', 'Cache-Control header was set to prevent caching.');
273
      $this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
274

    
275
      // Make sure that a second request to the already existing derivate works
276
      // too.
277
      $this->drupalGet($generate_url);
278
      $this->assertResponse(200, 'Image was generated at the URL.');
279

    
280
      // Make sure that access is denied for existing style files if we do not
281
      // have access.
282
      variable_del('image_module_test_file_download');
283
      $this->drupalGet($generate_url);
284
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
285

    
286
      // Repeat this with a different file that we do not have access to and
287
      // make sure that access is denied.
288
      $file_noaccess = array_shift($files);
289
      $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
290
      $generated_uri_noaccess = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/'. drupal_basename($original_uri_noaccess);
291
      $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
292
      $generate_url_noaccess = image_style_url($this->style_name, $original_uri_noaccess);
293

    
294
      $this->drupalGet($generate_url_noaccess);
295
      $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
296
      // Verify that images are not appended to the response. Currently this test only uses PNG images.
297
      if (strpos($generate_url, '.png') === FALSE ) {
298
        $this->fail('Confirming that private image styles are not appended require PNG file.');
299
      }
300
      else {
301
        // Check for PNG-Signature (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2) in the
302
        // response body.
303
        $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.');
304
      }
305
    }
306
    elseif ($clean_url) {
307
      // Add some extra chars to the token.
308
      $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
309
      $this->assertResponse(200, 'Existing image was accessible at the URL with an invalid token.');
310
    }
311

    
312
    // Allow insecure image derivatives to be created for the remainder of this
313
    // test.
314
    variable_set('image_allow_insecure_derivatives', TRUE);
315

    
316
    // Create another working copy of the file.
317
    $files = $this->drupalGetTestFiles('image');
318
    $file = array_shift($files);
319
    $image_info = image_get_info($file->uri);
320
    $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
321
    // Let the image_module_test module know about this file, so it can claim
322
    // ownership in hook_file_download().
323
    variable_set('image_module_test_file_download', $original_uri);
324

    
325
    // Get the URL of a file that has not been generated and try to create it.
326
    $generated_uri = image_style_path($this->style_name, $original_uri);
327
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
328
    $generate_url = image_style_url($this->style_name, $original_uri);
329

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

    
334
    // Check that a security token is still required when generating a second
335
    // image derivative using the first one as a source.
336
    $nested_uri = image_style_path($this->style_name, $generated_uri);
337
    $nested_url = image_style_url($this->style_name, $generated_uri);
338
    $nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $nested_url);
339
    $this->drupalGet($nested_url_with_wrong_token);
340
    $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token.');
341
    // Check that this restriction cannot be bypassed by adding extra slashes
342
    // to the URL.
343
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
344
    $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.');
345
    $this->drupalGet(substr_replace($nested_url_with_wrong_token, '/\styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
346
    $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.');
347
    // Make sure the image can still be generated if a correct token is used.
348
    $this->drupalGet($nested_url);
349
    $this->assertResponse(200, 'Image was accessible when a correct token was provided in the URL.');
350

    
351
    // Suppress the security token in the URL, then get the URL of a file. Check
352
    // that the security token is not present in the URL but that the image is
353
    // still accessible.
354
    variable_set('image_suppress_itok_output', TRUE);
355
    $generate_url = image_style_url($this->style_name, $original_uri);
356
    $this->assertIdentical(strpos($generate_url, IMAGE_DERIVATIVE_TOKEN . '='), FALSE, 'The security token does not appear in the image style URL.');
357
    $this->drupalGet($generate_url);
358
    $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
359

    
360
    // Check that requesting a nonexistent image does not create any new
361
    // directories in the file system.
362
    $directory = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/' . $this->randomName();
363
    $this->drupalGet(file_create_url($directory . '/' . $this->randomName()));
364
    $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
365
  }
366
}
367

    
368
/**
369
 * Use the image_test.module's mock toolkit to ensure that the effects are
370
 * properly passing parameters to the image toolkit.
371
 */
372
class ImageEffectsUnitTest extends ImageToolkitTestCase {
373
  public static function getInfo() {
374
    return array(
375
      'name' => 'Image effects',
376
      'description' => 'Test that the image effects pass parameters to the toolkit correctly.',
377
      'group' => 'Image',
378
    );
379
  }
380

    
381
  function setUp() {
382
    parent::setUp('image_module_test');
383
    module_load_include('inc', 'image', 'image.effects');
384
  }
385

    
386
  /**
387
   * Test the image_resize_effect() function.
388
   */
389
  function testResizeEffect() {
390
    $this->assertTrue(image_resize_effect($this->image, array('width' => 1, 'height' => 2)), 'Function returned the expected value.');
391
    $this->assertToolkitOperationsCalled(array('resize'));
392

    
393
    // Check the parameters.
394
    $calls = image_test_get_all_calls();
395
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
396
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
397
  }
398

    
399
  /**
400
   * Test the image_scale_effect() function.
401
   */
402
  function testScaleEffect() {
403
    // @todo: need to test upscaling.
404
    $this->assertTrue(image_scale_effect($this->image, array('width' => 10, 'height' => 10)), 'Function returned the expected value.');
405
    $this->assertToolkitOperationsCalled(array('resize'));
406

    
407
    // Check the parameters.
408
    $calls = image_test_get_all_calls();
409
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
410
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
411
  }
412

    
413
  /**
414
   * Test the image_crop_effect() function.
415
   */
416
  function testCropEffect() {
417
    // @todo should test the keyword offsets.
418
    $this->assertTrue(image_crop_effect($this->image, array('anchor' => 'top-1', 'width' => 3, 'height' => 4)), 'Function returned the expected value.');
419
    $this->assertToolkitOperationsCalled(array('crop'));
420

    
421
    // Check the parameters.
422
    $calls = image_test_get_all_calls();
423
    $this->assertEqual($calls['crop'][0][1], 0, 'X was passed correctly');
424
    $this->assertEqual($calls['crop'][0][2], 1, 'Y was passed correctly');
425
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
426
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
427
  }
428

    
429
  /**
430
   * Test the image_scale_and_crop_effect() function.
431
   */
432
  function testScaleAndCropEffect() {
433
    $this->assertTrue(image_scale_and_crop_effect($this->image, array('width' => 5, 'height' => 10)), 'Function returned the expected value.');
434
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));
435

    
436
    // Check the parameters.
437
    $calls = image_test_get_all_calls();
438
    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
439
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
440
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
441
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
442
  }
443

    
444
  /**
445
   * Test the image_desaturate_effect() function.
446
   */
447
  function testDesaturateEffect() {
448
    $this->assertTrue(image_desaturate_effect($this->image, array()), 'Function returned the expected value.');
449
    $this->assertToolkitOperationsCalled(array('desaturate'));
450

    
451
    // Check the parameters.
452
    $calls = image_test_get_all_calls();
453
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
454
  }
455

    
456
  /**
457
   * Test the image_rotate_effect() function.
458
   */
459
  function testRotateEffect() {
460
    // @todo: need to test with 'random' => TRUE
461
    $this->assertTrue(image_rotate_effect($this->image, array('degrees' => 90, 'bgcolor' => '#fff')), 'Function returned the expected value.');
462
    $this->assertToolkitOperationsCalled(array('rotate'));
463

    
464
    // Check the parameters.
465
    $calls = image_test_get_all_calls();
466
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
467
    $this->assertEqual($calls['rotate'][0][2], 0xffffff, 'Background color was passed correctly');
468
  }
469

    
470
  /**
471
   * Test image effect caching.
472
   */
473
  function testImageEffectsCaching() {
474
    $image_effect_definitions_called = &drupal_static('image_module_test_image_effect_info_alter');
475

    
476
    // First call should grab a fresh copy of the data.
477
    $effects = image_effect_definitions();
478
    $this->assertTrue($image_effect_definitions_called === 1, 'image_effect_definitions() generated data.');
479

    
480
    // Second call should come from cache.
481
    drupal_static_reset('image_effect_definitions');
482
    drupal_static_reset('image_module_test_image_effect_info_alter');
483
    $cached_effects = image_effect_definitions();
484
    $this->assertTrue(is_null($image_effect_definitions_called), 'image_effect_definitions() returned data from cache.');
485

    
486
    $this->assertTrue($effects == $cached_effects, 'Cached effects are the same as generated effects.');
487
  }
488
}
489

    
490
/**
491
 * Tests the administrative user interface.
492
 */
493
class ImageAdminUiTestCase extends ImageFieldTestCase {
494
  public static function getInfo() {
495
    return array(
496
      'name' => 'Administrative user interface',
497
      'description' => 'Tests the forms used in the administrative user interface.',
498
      'group' => 'Image',
499
    );
500
  }
501

    
502
  function setUp() {
503
    parent::setUp(array('image'));
504
  }
505

    
506
  /**
507
   * Test if the help text is available on the add effect form.
508
   */
509
  function testAddEffectHelpText() {
510
    // Create a random image style.
511
    $style = $this->createRandomStyle();
512

    
513
    // Open the add effect form and check for the help text.
514
    $this->drupalGet($style['path'] . '/add/image_crop');
515
    $this->assertText(t('Cropping will remove portions of an image to make it the specified dimensions.'), 'The image style effect help text was displayed on the add effect page.');
516
  }
517

    
518
  /**
519
   * Test if the help text is available on the edit effect form.
520
   */
521
  function testEditEffectHelpText() {
522
    // Create a random image style.
523
    $random_style = $this->createRandomStyle();
524

    
525
    // Add the crop effect to the image style.
526
    $edit = array();
527
    $edit['data[width]'] = 20;
528
    $edit['data[height]'] = 20;
529
    $this->drupalPost($random_style['path'] . '/add/image_crop', $edit, t('Add effect'));
530

    
531
    // Open the edit effect form and check for the help text.
532
    drupal_static_reset('image_styles');
533
    $style = image_style_load($random_style['name']);
534

    
535
    foreach ($style['effects'] as $ieid => $effect) {
536
      $this->drupalGet($random_style['path'] . '/effects/' . $ieid);
537
      $this->assertText(t('Cropping will remove portions of an image to make it the specified dimensions.'), 'The image style effect help text was displayed on the edit effect page.');
538
    }
539
  }
540
}
541

    
542
/**
543
 * Tests creation, deletion, and editing of image styles and effects.
544
 */
545
class ImageAdminStylesUnitTest extends ImageFieldTestCase {
546

    
547
  public static function getInfo() {
548
    return array(
549
      'name' => 'Image styles and effects UI configuration',
550
      'description' => 'Tests creation, deletion, and editing of image styles and effects at the UI level.',
551
      'group' => 'Image',
552
    );
553
  }
554

    
555
  /**
556
   * Given an image style, generate an image.
557
   */
558
  function createSampleImage($style) {
559
    static $file_path;
560

    
561
    // First, we need to make sure we have an image in our testing
562
    // file directory. Copy over an image on the first run.
563
    if (!isset($file_path)) {
564
      $files = $this->drupalGetTestFiles('image');
565
      $file = reset($files);
566
      $file_path = file_unmanaged_copy($file->uri);
567
    }
568

    
569
    return image_style_url($style['name'], $file_path) ? $file_path : FALSE;
570
  }
571

    
572
  /**
573
   * Count the number of images currently create for a style.
574
   */
575
  function getImageCount($style) {
576
    return count(file_scan_directory('public://styles/' . $style['name'], '/.*/'));
577
  }
578

    
579
  /**
580
   * Test creating an image style with a numeric name and ensuring it can be
581
   * applied to an image.
582
   */
583
  function testNumericStyleName() {
584
    $style_name = rand();
585
    $style_label = $this->randomString();
586
    $edit = array(
587
      'name' => $style_name,
588
      'label' => $style_label,
589
    );
590
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
591
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
592
    $options = image_style_options();
593
    $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', array('%key' => $style_name)));
594
  }
595

    
596
  /**
597
   * General test to add a style, add/remove/edit effects to it, then delete it.
598
   */
599
  function testStyle() {
600
    // Setup a style to be created and effects to add to it.
601
    $style_name = strtolower($this->randomName(10));
602
    $style_label = $this->randomString();
603
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
604
    $effect_edits = array(
605
      'image_resize' => array(
606
        'data[width]' => 100,
607
        'data[height]' => 101,
608
      ),
609
      'image_scale' => array(
610
        'data[width]' => 110,
611
        'data[height]' => 111,
612
        'data[upscale]' => 1,
613
      ),
614
      'image_scale_and_crop' => array(
615
        'data[width]' => 120,
616
        'data[height]' => 121,
617
      ),
618
      'image_crop' => array(
619
        'data[width]' => 130,
620
        'data[height]' => 131,
621
        'data[anchor]' => 'center-center',
622
      ),
623
      'image_desaturate' => array(
624
        // No options for desaturate.
625
      ),
626
      'image_rotate' => array(
627
        'data[degrees]' => 5,
628
        'data[random]' => 1,
629
        'data[bgcolor]' => '#FFFF00',
630
      ),
631
    );
632

    
633
    // Add style form.
634

    
635
    $edit = array(
636
      'name' => $style_name,
637
      'label' => $style_label,
638
    );
639
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
640
    $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
641

    
642
    // Add effect form.
643

    
644
    // Add each sample effect to the style.
645
    foreach ($effect_edits as $effect => $edit) {
646
      // Add the effect.
647
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
648
      if (!empty($edit)) {
649
        $this->drupalPost(NULL, $edit, t('Add effect'));
650
      }
651
    }
652

    
653
    // Edit effect form.
654

    
655
    // Revisit each form to make sure the effect was saved.
656
    drupal_static_reset('image_styles');
657
    $style = image_style_load($style_name);
658

    
659
    foreach ($style['effects'] as $ieid => $effect) {
660
      $this->drupalGet($style_path . '/effects/' . $ieid);
661
      foreach ($effect_edits[$effect['name']] as $field => $value) {
662
        $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)));
663
      }
664
    }
665

    
666
    // Image style overview form (ordering and renaming).
667

    
668
    // Confirm the order of effects is maintained according to the order we
669
    // added the fields.
670
    $effect_edits_order = array_keys($effect_edits);
671
    $effects_order = array_values($style['effects']);
672
    $order_correct = TRUE;
673
    foreach ($effects_order as $index => $effect) {
674
      if ($effect_edits_order[$index] != $effect['name']) {
675
        $order_correct = FALSE;
676
      }
677
    }
678
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
679

    
680
    // Test the style overview form.
681
    // Change the name of the style and adjust the weights of effects.
682
    $style_name = strtolower($this->randomName(10));
683
    $style_label = $this->randomString();
684
    $weight = count($effect_edits);
685
    $edit = array(
686
      'name' => $style_name,
687
      'label' => $style_label,
688
    );
689
    foreach ($style['effects'] as $ieid => $effect) {
690
      $edit['effects[' . $ieid . '][weight]'] = $weight;
691
      $weight--;
692
    }
693

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

    
698
    $this->drupalPost($style_path, $edit, t('Update style'));
699

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

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

    
707
    // Check that the image was flushed after updating the style.
708
    // This is especially important when renaming the style. Make sure that
709
    // the old image directory has been deleted.
710
    $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'])));
711

    
712
    // Load the style by the new name with the new weights.
713
    drupal_static_reset('image_styles');
714
    $style = image_style_load($style_name, NULL);
715

    
716
    // Confirm the new style order was saved.
717
    $effect_edits_order = array_reverse($effect_edits_order);
718
    $effects_order = array_values($style['effects']);
719
    $order_correct = TRUE;
720
    foreach ($effects_order as $index => $effect) {
721
      if ($effect_edits_order[$index] != $effect['name']) {
722
        $order_correct = FALSE;
723
      }
724
    }
725
    $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
726

    
727
    // Image effect deletion form.
728

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

    
733
    // Test effect deletion form.
734
    $effect = array_pop($style['effects']);
735
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
736
    $this->assertRaw(t('The image effect %name has been deleted.', array('%name' => $effect['label'])), 'Image effect deleted.');
737

    
738
    // Style deletion form.
739

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

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

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

    
750
  }
751

    
752
  /**
753
   * Test to override, edit, then revert a style.
754
   */
755
  function testDefaultStyle() {
756
    // Setup a style to be created and effects to add to it.
757
    $style_name = 'thumbnail';
758
    $style_label = 'Thumbnail (100x100)';
759
    $edit_path = 'admin/config/media/image-styles/edit/' . $style_name;
760
    $delete_path = 'admin/config/media/image-styles/delete/' . $style_name;
761
    $revert_path = 'admin/config/media/image-styles/revert/' . $style_name;
762

    
763
    // Ensure deleting a default is not possible.
764
    $this->drupalGet($delete_path);
765
    $this->assertText(t('Page not found'), 'Default styles may not be deleted.');
766

    
767
    // Ensure that editing a default is not possible (without overriding).
768
    $this->drupalGet($edit_path);
769
    $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
770
    $this->assertTrue($disabled_field, 'Default styles may not be renamed.');
771
    $this->assertNoField('edit-submit', 'Default styles may not be edited.');
772
    $this->assertNoField('edit-add', 'Default styles may not have new effects added.');
773

    
774
    // Create an image to make sure the default works before overriding.
775
    drupal_static_reset('image_styles');
776
    $style = image_style_load($style_name);
777
    $image_path = $this->createSampleImage($style);
778
    $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
779

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

    
785
    // Override the default.
786
    $this->drupalPost($edit_path, array(), t('Override defaults'));
787
    $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.');
788

    
789
    // Add sample effect to the overridden style.
790
    $this->drupalPost($edit_path, array('new' => 'image_desaturate'), t('Add'));
791
    drupal_static_reset('image_styles');
792
    $style = image_style_load($style_name);
793

    
794
    // Verify that effects attached to the style have an ieid now.
795
    foreach ($style['effects'] as $effect) {
796
      $this->assertTrue(isset($effect['ieid']), format_string('The %effect effect has an ieid.', array('%effect' => $effect['name'])));
797
    }
798

    
799
    // The style should now have 2 effect, the original scale provided by core
800
    // and the desaturate effect we added in the override.
801
    $effects = array_values($style['effects']);
802
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the overridden style.');
803
    $this->assertEqual($effects[1]['name'], 'image_desaturate', 'The added effect exists in the overridden style.');
804

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

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

    
814
    // Revert the image style.
815
    $this->drupalPost($revert_path, array(), t('Revert'));
816
    drupal_static_reset('image_styles');
817
    $style = image_style_load($style_name);
818

    
819
    // The style should now have the single effect for scale.
820
    $effects = array_values($style['effects']);
821
    $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the reverted style.');
822
    $this->assertFalse(array_key_exists(1, $effects), 'The added effect has been removed in the reverted style.');
823
  }
824

    
825
  /**
826
   * Test deleting a style and choosing a replacement style.
827
   */
828
  function testStyleReplacement() {
829
    // Create a new style.
830
    $style_name = strtolower($this->randomName(10));
831
    $style_label = $this->randomString();
832
    image_style_save(array('name' => $style_name, 'label' => $style_label));
833
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
834

    
835
    // Create an image field that uses the new style.
836
    $field_name = strtolower($this->randomName(10));
837
    $this->createImageField($field_name, 'article');
838
    $instance = field_info_instance('node', $field_name, 'article');
839
    $instance['display']['default']['type'] = 'image';
840
    $instance['display']['default']['settings']['image_style'] = $style_name;
841
    field_update_instance($instance);
842

    
843
    // Create a new node with an image attached.
844
    $test_image = current($this->drupalGetTestFiles('image'));
845
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
846
    $node = node_load($nid);
847

    
848
    // Test that image is displayed using newly created style.
849
    $this->drupalGet('node/' . $nid);
850
    $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)));
851

    
852
    // Rename the style and make sure the image field is updated.
853
    $new_style_name = strtolower($this->randomName(10));
854
    $new_style_label = $this->randomString();
855
    $edit = array(
856
      'name' => $new_style_name,
857
      'label' => $new_style_label,
858
    );
859
    $this->drupalPost('admin/config/media/image-styles/edit/' . $style_name, $edit, t('Update style'));
860
    $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)));
861
    $this->drupalGet('node/' . $nid);
862
    $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.'));
863

    
864
    // Delete the style and choose a replacement style.
865
    $edit = array(
866
      'replacement' => 'thumbnail',
867
    );
868
    $this->drupalPost('admin/config/media/image-styles/delete/' . $new_style_name, $edit, t('Delete'));
869
    $message = t('Style %name was deleted.', array('%name' => $new_style_label));
870
    $this->assertRaw($message, $message);
871

    
872
    $this->drupalGet('node/' . $nid);
873
    $this->assertRaw(check_plain(image_style_url('thumbnail', $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
874
  }
875
}
876

    
877
/**
878
 * Test class to check that formatters and display settings are working.
879
 */
880
class ImageFieldDisplayTestCase extends ImageFieldTestCase {
881
  public static function getInfo() {
882
    return array(
883
      'name' => 'Image field display tests',
884
      'description' => 'Test the display of image fields.',
885
      'group' => 'Image',
886
    );
887
  }
888

    
889
  /**
890
   * Test image formatters on node display for public files.
891
   */
892
  function testImageFieldFormattersPublic() {
893
    $this->_testImageFieldFormatters('public');
894
  }
895

    
896
  /**
897
   * Test image formatters on node display for private files.
898
   */
899
  function testImageFieldFormattersPrivate() {
900
    // Remove access content permission from anonymous users.
901
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access content' => FALSE));
902
    $this->_testImageFieldFormatters('private');
903
  }
904

    
905
  /**
906
   * Test image formatters on node display.
907
   */
908
  function _testImageFieldFormatters($scheme) {
909
    $field_name = strtolower($this->randomName());
910
    $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme));
911
    // Create a new node with an image attached.
912
    $test_image = current($this->drupalGetTestFiles('image'));
913
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
914
    $node = node_load($nid, NULL, TRUE);
915

    
916
    // Test that the default formatter is being used.
917
    $image_uri = $node->{$field_name}[LANGUAGE_NONE][0]['uri'];
918
    $image_info = array(
919
      'path' => $image_uri,
920
      'width' => 40,
921
      'height' => 20,
922
    );
923
    $default_output = theme('image', $image_info);
924
    $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
925

    
926
    // Test the image linked to file formatter.
927
    $instance = field_info_instance('node', $field_name, 'article');
928
    $instance['display']['default']['type'] = 'image';
929
    $instance['display']['default']['settings']['image_link'] = 'file';
930
    field_update_instance($instance);
931
    $default_output = l(theme('image', $image_info), file_create_url($image_uri), array('html' => TRUE));
932
    $this->drupalGet('node/' . $nid);
933
    $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
934
    // Verify that the image can be downloaded.
935
    $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
936
    if ($scheme == 'private') {
937
      // Only verify HTTP headers when using private scheme and the headers are
938
      // sent by Drupal.
939
      $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
940
      $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'private', 'Cache-Control header was sent.');
941

    
942
      // Log out and try to access the file.
943
      $this->drupalLogout();
944
      $this->drupalGet(file_create_url($image_uri));
945
      $this->assertResponse('403', 'Access denied to original image as anonymous user.');
946

    
947
      // Log in again.
948
      $this->drupalLogin($this->admin_user);
949
    }
950

    
951
    // Test the image linked to content formatter.
952
    $instance['display']['default']['settings']['image_link'] = 'content';
953
    field_update_instance($instance);
954
    $default_output = l(theme('image', $image_info), 'node/' . $nid, array('html' => TRUE, 'attributes' => array('class' => 'active')));
955
    $this->drupalGet('node/' . $nid);
956
    $this->assertRaw($default_output, 'Image linked to content formatter displaying correctly on full node view.');
957

    
958
    // Test the image style 'thumbnail' formatter.
959
    $instance['display']['default']['settings']['image_link'] = '';
960
    $instance['display']['default']['settings']['image_style'] = 'thumbnail';
961
    field_update_instance($instance);
962
    // Ensure the derivative image is generated so we do not have to deal with
963
    // image style callback paths.
964
    $this->drupalGet(image_style_url('thumbnail', $image_uri));
965
    // Need to create the URL again since it will change if clean URLs
966
    // are disabled.
967
    $image_info['path'] = image_style_url('thumbnail', $image_uri);
968
    $image_info['width'] = 100;
969
    $image_info['height'] = 50;
970
    $default_output = theme('image', $image_info);
971
    $this->drupalGet('node/' . $nid);
972
    $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
973

    
974
    if ($scheme == 'private') {
975
      // Log out and try to access the file.
976
      $this->drupalLogout();
977
      $this->drupalGet(image_style_url('thumbnail', $image_uri));
978
      $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
979
    }
980
  }
981

    
982
  /**
983
   * Tests for image field settings.
984
   */
985
  function testImageFieldSettings() {
986
    $test_image = current($this->drupalGetTestFiles('image'));
987
    list(, $test_image_extension) = explode('.', $test_image->filename);
988
    $field_name = strtolower($this->randomName());
989
    $instance_settings = array(
990
      'alt_field' => 1,
991
      'file_extensions' => $test_image_extension,
992
      'max_filesize' => '50 KB',
993
      'max_resolution' => '100x100',
994
      'min_resolution' => '10x10',
995
      'title_field' => 1,
996
    );
997
    $widget_settings = array(
998
      'preview_image_style' => 'medium',
999
    );
1000
    $field = $this->createImageField($field_name, 'article', array(), $instance_settings, $widget_settings);
1001
    $field['deleted'] = 0;
1002
    $table = _field_sql_storage_tablename($field);
1003
    $schema = drupal_get_schema($table, TRUE);
1004
    $instance = field_info_instance('node', $field_name, 'article');
1005

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

    
1011
    // We have to create the article first and then edit it because the alt
1012
    // and title fields do not display until the image has been attached.
1013
    $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
1014
    $this->drupalGet('node/' . $nid . '/edit');
1015
    $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][alt]', '', 'Alt field displayed on article form.');
1016
    $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][title]', '', 'Title field displayed on article form.');
1017
    // Verify that the attached image is being previewed using the 'medium'
1018
    // style.
1019
    $node = node_load($nid, NULL, TRUE);
1020
    $image_info = array(
1021
      'path' => image_style_url('medium', $node->{$field_name}[LANGUAGE_NONE][0]['uri']),
1022
      'width' => 220,
1023
      'height' => 110,
1024
    );
1025
    $default_output = theme('image', $image_info);
1026
    $this->assertRaw($default_output, "Preview image is displayed using 'medium' style.");
1027

    
1028
    // Add alt/title fields to the image and verify that they are displayed.
1029
    $image_info = array(
1030
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
1031
      'alt' => $this->randomName(),
1032
      'title' => $this->randomName(),
1033
      'width' => 40,
1034
      'height' => 20,
1035
    );
1036
    $edit = array(
1037
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $image_info['alt'],
1038
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $image_info['title'],
1039
    );
1040
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
1041
    $default_output = theme('image', $image_info);
1042
    $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
1043

    
1044
    // Verify that alt/title longer than allowed results in a validation error.
1045
    $test_size = 2000;
1046
    $edit = array(
1047
      $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $this->randomName($test_size),
1048
      $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $this->randomName($test_size),
1049
    );
1050
    $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
1051
    $this->assertRaw(t('Alternate text cannot be longer than %max characters but is currently %length characters long.', array(
1052
      '%max' => $schema['fields'][$field_name .'_alt']['length'],
1053
      '%length' => $test_size,
1054
    )));
1055
    $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
1056
      '%max' => $schema['fields'][$field_name .'_title']['length'],
1057
      '%length' => $test_size,
1058
    )));
1059
  }
1060

    
1061
  /**
1062
   * Test passing attributes into the image field formatters.
1063
   */
1064
  function testImageFieldFormatterAttributes() {
1065
    $image = theme('image_formatter', array(
1066
      'item' => array(
1067
        'uri' => 'http://example.com/example.png',
1068
        'attributes' => array(
1069
          'data-image-field-formatter' => 'testFound',
1070
        ),
1071
        'alt' => t('Image field formatter attribute test.'),
1072
        'title' => t('Image field formatter'),
1073
      ),
1074
    ));
1075
    $this->assertTrue(stripos($image, 'testFound') > 0, 'Image field formatters can have attributes.');
1076
  }
1077

    
1078
  /**
1079
   * Test use of a default image with an image field.
1080
   */
1081
  function testImageFieldDefaultImage() {
1082
    // Create a new image field.
1083
    $field_name = strtolower($this->randomName());
1084
    $this->createImageField($field_name, 'article');
1085

    
1086
    // Create a new node, with no images and verify that no images are
1087
    // displayed.
1088
    $node = $this->drupalCreateNode(array('type' => 'article'));
1089
    $this->drupalGet('node/' . $node->nid);
1090
    // Verify that no image is displayed on the page by checking for the class
1091
    // that would be used on the image field.
1092
    $this->assertNoPattern('<div class="(.*?)field-name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
1093

    
1094
    // Add a default image to the public imagefield instance.
1095
    $images = $this->drupalGetTestFiles('image');
1096
    $edit = array(
1097
      'files[field_settings_default_image]' => drupal_realpath($images[0]->uri),
1098
    );
1099
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
1100
    // Clear field info cache so the new default image is detected.
1101
    field_info_cache_clear();
1102
    $field = field_info_field($field_name);
1103
    $image = file_load($field['settings']['default_image']);
1104
    $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
1105
    $default_output = theme('image', array('path' => $image->uri));
1106
    $this->drupalGet('node/' . $node->nid);
1107
    $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
1108

    
1109
    // Create a node with an image attached and ensure that the default image
1110
    // is not displayed.
1111
    $nid = $this->uploadNodeImage($images[1], $field_name, 'article');
1112
    $node = node_load($nid, NULL, TRUE);
1113
    $image_info = array(
1114
      'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
1115
      'width' => 40,
1116
      'height' => 20,
1117
    );
1118
    $image_output = theme('image', $image_info);
1119
    $this->drupalGet('node/' . $nid);
1120
    $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
1121
    $this->assertRaw($image_output, 'User supplied image is displayed.');
1122

    
1123
    // Remove default image from the field and make sure it is no longer used.
1124
    $edit = array(
1125
      'field[settings][default_image][fid]' => 0,
1126
    );
1127
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
1128
    // Clear field info cache so the new default image is detected.
1129
    field_info_cache_clear();
1130
    $field = field_info_field($field_name);
1131
    $this->assertFalse($field['settings']['default_image'], 'Default image removed from field.');
1132
    // Create an image field that uses the private:// scheme and test that the
1133
    // default image works as expected.
1134
    $private_field_name = strtolower($this->randomName());
1135
    $this->createImageField($private_field_name, 'article', array('uri_scheme' => 'private'));
1136
    // Add a default image to the new field.
1137
    $edit = array(
1138
      'files[field_settings_default_image]' => drupal_realpath($images[1]->uri),
1139
    );
1140
    $this->drupalPost('admin/structure/types/manage/article/fields/' . $private_field_name, $edit, t('Save settings'));
1141
    $private_field = field_info_field($private_field_name);
1142
    $image = file_load($private_field['settings']['default_image']);
1143
    $this->assertEqual('private', file_uri_scheme($image->uri), 'Default image uses private:// scheme.');
1144
    $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
1145
    // Create a new node with no image attached and ensure that default private
1146
    // image is displayed.
1147
    $node = $this->drupalCreateNode(array('type' => 'article'));
1148
    $default_output = theme('image', array('path' => $image->uri));
1149
    $this->drupalGet('node/' . $node->nid);
1150
    $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');
1151
  }
1152
}
1153

    
1154
/**
1155
 * Test class to check for various validations.
1156
 */
1157
class ImageFieldValidateTestCase extends ImageFieldTestCase {
1158
  public static function getInfo() {
1159
    return array(
1160
      'name' => 'Image field validation tests',
1161
      'description' => 'Tests validation functions such as min/max resolution.',
1162
      'group' => 'Image',
1163
    );
1164
  }
1165

    
1166
  /**
1167
   * Test min/max resolution settings.
1168
   */
1169
  function testResolution() {
1170
    $field_name = strtolower($this->randomName());
1171
    $min_resolution = 50;
1172
    $max_resolution = 100;
1173
    $instance_settings = array(
1174
      'max_resolution' => $max_resolution . 'x' . $max_resolution,
1175
      'min_resolution' => $min_resolution . 'x' . $min_resolution,
1176
    );
1177
    $this->createImageField($field_name, 'article', array(), $instance_settings);
1178

    
1179
    // We want a test image that is too small, and a test image that is too
1180
    // big, so cycle through test image files until we have what we need.
1181
    $image_that_is_too_big = FALSE;
1182
    $image_that_is_too_small = FALSE;
1183
    foreach ($this->drupalGetTestFiles('image') as $image) {
1184
      $info = image_get_info($image->uri);
1185
      if ($info['width'] > $max_resolution) {
1186
        $image_that_is_too_big = $image;
1187
      }
1188
      if ($info['width'] < $min_resolution) {
1189
        $image_that_is_too_small = $image;
1190
      }
1191
      if ($image_that_is_too_small && $image_that_is_too_big) {
1192
        break;
1193
      }
1194
    }
1195
    $nid = $this->uploadNodeImage($image_that_is_too_small, $field_name, 'article');
1196
    $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.');
1197
    $nid = $this->uploadNodeImage($image_that_is_too_big, $field_name, 'article');
1198
    $this->assertText(t('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.'), 'Image exceeding max resolution was properly resized.');
1199
  }
1200
}
1201

    
1202
/**
1203
 * Tests that images have correct dimensions when styled.
1204
 */
1205
class ImageDimensionsTestCase extends DrupalWebTestCase {
1206

    
1207
  public static function getInfo() {
1208
    return array(
1209
      'name' => 'Image dimensions',
1210
      'description' => 'Tests that images have correct dimensions when styled.',
1211
      'group' => 'Image',
1212
    );
1213
  }
1214

    
1215
  function setUp() {
1216
    parent::setUp('image_module_test');
1217
  }
1218

    
1219
  /**
1220
   * Test styled image dimensions cumulatively.
1221
   */
1222
  function testImageDimensions() {
1223
    // Create a working copy of the file.
1224
    $files = $this->drupalGetTestFiles('image');
1225
    $file = reset($files);
1226
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1227

    
1228
    // Create a style.
1229
    $style = image_style_save(array('name' => 'test', 'label' => 'Test'));
1230
    $generated_uri = 'public://styles/test/public/'. drupal_basename($original_uri);
1231
    $url = image_style_url('test', $original_uri);
1232

    
1233
    $variables = array(
1234
      'style_name' => 'test',
1235
      'path' => $original_uri,
1236
      'width' => 40,
1237
      'height' => 20,
1238
    );
1239

    
1240
    // Scale an image that is wider than it is high.
1241
    $effect = array(
1242
      'name' => 'image_scale',
1243
      'data' => array(
1244
        'width' => 120,
1245
        'height' => 90,
1246
        'upscale' => TRUE,
1247
      ),
1248
      'isid' => $style['isid'],
1249
    );
1250

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

    
1262
    // Rotate 90 degrees anticlockwise.
1263
    $effect = array(
1264
      'name' => 'image_rotate',
1265
      'data' => array(
1266
        'degrees' => -90,
1267
        'random' => FALSE,
1268
      ),
1269
      'isid' => $style['isid'],
1270
    );
1271

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

    
1283
    // Scale an image that is higher than it is wide (rotated by previous effect).
1284
    $effect = array(
1285
      'name' => 'image_scale',
1286
      'data' => array(
1287
        'width' => 120,
1288
        'height' => 90,
1289
        'upscale' => TRUE,
1290
      ),
1291
      'isid' => $style['isid'],
1292
    );
1293

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

    
1305
    // Test upscale disabled.
1306
    $effect = array(
1307
      'name' => 'image_scale',
1308
      'data' => array(
1309
        'width' => 400,
1310
        'height' => 200,
1311
        'upscale' => FALSE,
1312
      ),
1313
      'isid' => $style['isid'],
1314
    );
1315

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

    
1327
    // Add a desaturate effect.
1328
    $effect = array(
1329
      'name' => 'image_desaturate',
1330
      'data' => array(),
1331
      'isid' => $style['isid'],
1332
    );
1333

    
1334
    image_effect_save($effect);
1335
    $img_tag = theme_image_style($variables);
1336
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
1337
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1338
    $this->drupalGet($url);
1339
    $this->assertResponse(200, 'Image was generated at the URL.');
1340
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1341
    $image_info = image_get_info($generated_uri);
1342
    $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
1343
    $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
1344

    
1345
    // Add a random rotate effect.
1346
    $effect = array(
1347
      'name' => 'image_rotate',
1348
      'data' => array(
1349
        'degrees' => 180,
1350
        'random' => TRUE,
1351
      ),
1352
      'isid' => $style['isid'],
1353
    );
1354

    
1355
    image_effect_save($effect);
1356
    $img_tag = theme_image_style($variables);
1357
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1358
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1359
    $this->drupalGet($url);
1360
    $this->assertResponse(200, 'Image was generated at the URL.');
1361
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1362

    
1363

    
1364
    // Add a crop effect.
1365
    $effect = array(
1366
      'name' => 'image_crop',
1367
      'data' => array(
1368
        'width' => 30,
1369
        'height' => 30,
1370
        'anchor' => 'center-center',
1371
      ),
1372
      'isid' => $style['isid'],
1373
    );
1374

    
1375
    image_effect_save($effect);
1376
    $img_tag = theme_image_style($variables);
1377
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="30" height="30" alt="" />', 'Expected img tag was found.');
1378
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1379
    $this->drupalGet($url);
1380
    $this->assertResponse(200, 'Image was generated at the URL.');
1381
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1382
    $image_info = image_get_info($generated_uri);
1383
    $this->assertEqual($image_info['width'], 30, 'Expected width was found.');
1384
    $this->assertEqual($image_info['height'], 30, 'Expected height was found.');
1385

    
1386
    // Rotate to a non-multiple of 90 degrees.
1387
    $effect = array(
1388
      'name' => 'image_rotate',
1389
      'data' => array(
1390
        'degrees' => 57,
1391
        'random' => FALSE,
1392
      ),
1393
      'isid' => $style['isid'],
1394
    );
1395

    
1396
    $effect = image_effect_save($effect);
1397
    $img_tag = theme_image_style($variables);
1398
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1399
    $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
1400
    $this->drupalGet($url);
1401
    $this->assertResponse(200, 'Image was generated at the URL.');
1402
    $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
1403

    
1404
    image_effect_delete($effect);
1405

    
1406
    // Ensure that an effect with no dimensions callback unsets the dimensions.
1407
    // This ensures compatibility with 7.0 contrib modules.
1408
    $effect = array(
1409
      'name' => 'image_module_test_null',
1410
      'data' => array(),
1411
      'isid' => $style['isid'],
1412
    );
1413

    
1414
    image_effect_save($effect);
1415
    $img_tag = theme_image_style($variables);
1416
    $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
1417
  }
1418
}
1419

    
1420
/**
1421
 * Tests image_dimensions_scale().
1422
 */
1423
class ImageDimensionsScaleTestCase extends DrupalUnitTestCase {
1424
  public static function getInfo() {
1425
    return array(
1426
      'name' => 'image_dimensions_scale()',
1427
      'description' => 'Tests all control flow branches in image_dimensions_scale().',
1428
      'group' => 'Image',
1429
    );
1430
  }
1431

    
1432
  /**
1433
   * Tests all control flow branches in image_dimensions_scale().
1434
   */
1435
  function testImageDimensionsScale() {
1436
    // Define input / output datasets to test different branch conditions.
1437
    $test = array();
1438

    
1439
    // Test branch conditions:
1440
    // - No height.
1441
    // - Upscale, don't need to upscale.
1442
    $tests[] = array(
1443
      'input' => array(
1444
        'dimensions' => array(
1445
          'width' => 1000,
1446
          'height' => 2000,
1447
        ),
1448
        'width' => 200,
1449
        'height' => NULL,
1450
        'upscale' => TRUE,
1451
      ),
1452
      'output' => array(
1453
        'dimensions' => array(
1454
          'width' => 200,
1455
          'height' => 400,
1456
        ),
1457
        'return_value' => TRUE,
1458
      ),
1459
    );
1460

    
1461
    // Test branch conditions:
1462
    // - No width.
1463
    // - Don't upscale, don't need to upscale.
1464
    $tests[] = array(
1465
      'input' => array(
1466
        'dimensions' => array(
1467
          'width' => 1000,
1468
          'height' => 800,
1469
        ),
1470
        'width' => NULL,
1471
        'height' => 140,
1472
        'upscale' => FALSE,
1473
      ),
1474
      'output' => array(
1475
        'dimensions' => array(
1476
          'width' => 175,
1477
          'height' => 140,
1478
        ),
1479
        'return_value' => TRUE,
1480
      ),
1481
    );
1482

    
1483
    // Test branch conditions:
1484
    // - Source aspect ratio greater than target.
1485
    // - Upscale, need to upscale.
1486
    $tests[] = array(
1487
      'input' => array(
1488
        'dimensions' => array(
1489
          'width' => 8,
1490
          'height' => 20,
1491
        ),
1492
        'width' => 200,
1493
        'height' => 140,
1494
        'upscale' => TRUE,
1495
      ),
1496
      'output' => array(
1497
        'dimensions' => array(
1498
          'width' => 56,
1499
          'height' => 140,
1500
        ),
1501
        'return_value' => TRUE,
1502
      ),
1503
    );
1504

    
1505
    // Test branch condition: target aspect ratio greater than source.
1506
    $tests[] = array(
1507
      'input' => array(
1508
        'dimensions' => array(
1509
          'width' => 2000,
1510
          'height' => 800,
1511
        ),
1512
        'width' => 200,
1513
        'height' => 140,
1514
        'upscale' => FALSE,
1515
      ),
1516
      'output' => array(
1517
        'dimensions' => array(
1518
          'width' => 200,
1519
          'height' => 80,
1520
        ),
1521
        'return_value' => TRUE,
1522
      ),
1523
    );
1524

    
1525
    // Test branch condition: don't upscale, need to upscale.
1526
    $tests[] = array(
1527
      'input' => array(
1528
        'dimensions' => array(
1529
          'width' => 100,
1530
          'height' => 50,
1531
        ),
1532
        'width' => 200,
1533
        'height' => 140,
1534
        'upscale' => FALSE,
1535
      ),
1536
      'output' => array(
1537
        'dimensions' => array(
1538
          'width' => 100,
1539
          'height' => 50,
1540
        ),
1541
        'return_value' => FALSE,
1542
      ),
1543
    );
1544

    
1545
    foreach ($tests as $test) {
1546
      // Process the test dataset.
1547
      $return_value = image_dimensions_scale($test['input']['dimensions'], $test['input']['width'], $test['input']['height'], $test['input']['upscale']);
1548

    
1549
      // Check the width.
1550
      $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'])));
1551

    
1552
      // Check the height.
1553
      $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'])));
1554

    
1555
      // Check the return value.
1556
      $this->assertEqual($test['output']['return_value'], $return_value, 'Correct return value.');
1557
    }
1558
  }
1559
}
1560

    
1561
/**
1562
 * Tests default image settings.
1563
 */
1564
class ImageFieldDefaultImagesTestCase extends ImageFieldTestCase {
1565

    
1566
  public static function getInfo() {
1567
    return array(
1568
      'name' => 'Image field default images tests',
1569
      'description' => 'Tests setting up default images both to the field and field instance.',
1570
      'group' => 'Image',
1571
    );
1572
  }
1573

    
1574
  function setUp() {
1575
    parent::setUp(array('field_ui'));
1576
  }
1577

    
1578
  /**
1579
   * Tests CRUD for fields and fields instances with default images.
1580
   */
1581
  function testDefaultImages() {
1582
    // Create files to use as the default images.
1583
    $files = $this->drupalGetTestFiles('image');
1584
    $default_images = array();
1585
    foreach (array('field', 'instance', 'instance2', 'field_new', 'instance_new') as $image_target) {
1586
      $file = array_pop($files);
1587
      $file = file_save($file);
1588
      $default_images[$image_target] = $file;
1589
    }
1590

    
1591
    // Create an image field and add an instance to the article content type.
1592
    $field_name = strtolower($this->randomName());
1593
    $field_settings = array(
1594
      'default_image' => $default_images['field']->fid,
1595
    );
1596
    $instance_settings = array(
1597
      'default_image' => $default_images['instance']->fid,
1598
    );
1599
    $widget_settings = array(
1600
      'preview_image_style' => 'medium',
1601
    );
1602
    $this->createImageField($field_name, 'article', $field_settings, $instance_settings, $widget_settings);
1603
    $field = field_info_field($field_name);
1604
    $instance = field_info_instance('node', $field_name, 'article');
1605

    
1606
    // Add another instance with another default image to the page content type.
1607
    $instance2 = array_merge($instance, array(
1608
      'bundle' => 'page',
1609
      'settings' => array(
1610
        'default_image' => $default_images['instance2']->fid,
1611
      ),
1612
    ));
1613
    field_create_instance($instance2);
1614
    $instance2 = field_info_instance('node', $field_name, 'page');
1615

    
1616

    
1617
    // Confirm the defaults are present on the article field admin form.
1618
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1619
    $this->assertFieldByXpath(
1620
      '//input[@name="field[settings][default_image][fid]"]',
1621
      $default_images['field']->fid,
1622
      format_string(
1623
        'Article image field default equals expected file ID of @fid.',
1624
        array('@fid' => $default_images['field']->fid)
1625
      )
1626
    );
1627
    $this->assertFieldByXpath(
1628
      '//input[@name="instance[settings][default_image][fid]"]',
1629
      $default_images['instance']->fid,
1630
      format_string(
1631
        'Article image field instance default equals expected file ID of @fid.',
1632
        array('@fid' => $default_images['instance']->fid)
1633
      )
1634
    );
1635

    
1636
    // Confirm the defaults are present on the page field admin form.
1637
    $this->drupalGet("admin/structure/types/manage/page/fields/$field_name");
1638
    $this->assertFieldByXpath(
1639
      '//input[@name="field[settings][default_image][fid]"]',
1640
      $default_images['field']->fid,
1641
      format_string(
1642
        'Page image field default equals expected file ID of @fid.',
1643
        array('@fid' => $default_images['field']->fid)
1644
      )
1645
    );
1646
    $this->assertFieldByXpath(
1647
      '//input[@name="instance[settings][default_image][fid]"]',
1648
      $default_images['instance2']->fid,
1649
      format_string(
1650
        'Page image field instance default equals expected file ID of @fid.',
1651
        array('@fid' => $default_images['instance2']->fid)
1652
      )
1653
    );
1654

    
1655
    // Confirm that the image default is shown for a new article node.
1656
    $article = $this->drupalCreateNode(array('type' => 'article'));
1657
    $article_built = node_view($article);
1658
    $this->assertEqual(
1659
      $article_built[$field_name]['#items'][0]['fid'],
1660
      $default_images['instance']->fid,
1661
      format_string(
1662
        'A new article node without an image has the expected default image file ID of @fid.',
1663
        array('@fid' => $default_images['instance']->fid)
1664
      )
1665
    );
1666

    
1667
    // Confirm that the image default is shown for a new page node.
1668
    $page = $this->drupalCreateNode(array('type' => 'page'));
1669
    $page_built = node_view($page);
1670
    $this->assertEqual(
1671
      $page_built[$field_name]['#items'][0]['fid'],
1672
      $default_images['instance2']->fid,
1673
      format_string(
1674
        'A new page node without an image has the expected default image file ID of @fid.',
1675
        array('@fid' => $default_images['instance2']->fid)
1676
      )
1677
    );
1678

    
1679
    // Upload a new default for the field.
1680
    $field['settings']['default_image'] = $default_images['field_new']->fid;
1681
    field_update_field($field);
1682

    
1683
    // Confirm that the new field default is used on the article admin form.
1684
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1685
    $this->assertFieldByXpath(
1686
      '//input[@name="field[settings][default_image][fid]"]',
1687
      $default_images['field_new']->fid,
1688
      format_string(
1689
        'Updated image field default equals expected file ID of @fid.',
1690
        array('@fid' => $default_images['field_new']->fid)
1691
      )
1692
    );
1693

    
1694
    // Reload the nodes and confirm the field instance defaults are used.
1695
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1696
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1697
    $this->assertEqual(
1698
      $article_built[$field_name]['#items'][0]['fid'],
1699
      $default_images['instance']->fid,
1700
      format_string(
1701
        'An existing article node without an image has the expected default image file ID of @fid.',
1702
        array('@fid' => $default_images['instance']->fid)
1703
      )
1704
    );
1705
    $this->assertEqual(
1706
      $page_built[$field_name]['#items'][0]['fid'],
1707
      $default_images['instance2']->fid,
1708
      format_string(
1709
        'An existing page node without an image has the expected default image file ID of @fid.',
1710
        array('@fid' => $default_images['instance2']->fid)
1711
      )
1712
    );
1713

    
1714
    // Upload a new default for the article's field instance.
1715
    $instance['settings']['default_image'] = $default_images['instance_new']->fid;
1716
    field_update_instance($instance);
1717

    
1718
    // Confirm the new field instance default is used on the article field
1719
    // admin form.
1720
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1721
    $this->assertFieldByXpath(
1722
      '//input[@name="instance[settings][default_image][fid]"]',
1723
      $default_images['instance_new']->fid,
1724
      format_string(
1725
        'Updated article image field instance default equals expected file ID of @fid.',
1726
        array('@fid' => $default_images['instance_new']->fid)
1727
      )
1728
    );
1729

    
1730
    // Reload the nodes.
1731
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1732
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1733

    
1734
    // Confirm the article uses the new default.
1735
    $this->assertEqual(
1736
      $article_built[$field_name]['#items'][0]['fid'],
1737
      $default_images['instance_new']->fid,
1738
      format_string(
1739
        'An existing article node without an image has the expected default image file ID of @fid.',
1740
        array('@fid' => $default_images['instance_new']->fid)
1741
      )
1742
    );
1743
    // Confirm the page remains unchanged.
1744
    $this->assertEqual(
1745
      $page_built[$field_name]['#items'][0]['fid'],
1746
      $default_images['instance2']->fid,
1747
      format_string(
1748
        'An existing page node without an image has the expected default image file ID of @fid.',
1749
        array('@fid' => $default_images['instance2']->fid)
1750
      )
1751
    );
1752

    
1753
    // Remove the instance default from articles.
1754
    $instance['settings']['default_image'] = NULL;
1755
    field_update_instance($instance);
1756

    
1757
    // Confirm the article field instance default has been removed.
1758
    $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
1759
    $this->assertFieldByXpath(
1760
      '//input[@name="instance[settings][default_image][fid]"]',
1761
      '',
1762
      'Updated article image field instance default has been successfully removed.'
1763
    );
1764

    
1765
    // Reload the nodes.
1766
    $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
1767
    $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
1768
    // Confirm the article uses the new field (not instance) default.
1769
    $this->assertEqual(
1770
      $article_built[$field_name]['#items'][0]['fid'],
1771
      $default_images['field_new']->fid,
1772
      format_string(
1773
        'An existing article node without an image has the expected default image file ID of @fid.',
1774
        array('@fid' => $default_images['field_new']->fid)
1775
      )
1776
    );
1777
    // Confirm the page remains unchanged.
1778
    $this->assertEqual(
1779
      $page_built[$field_name]['#items'][0]['fid'],
1780
      $default_images['instance2']->fid,
1781
      format_string(
1782
        'An existing page node without an image has the expected default image file ID of @fid.',
1783
        array('@fid' => $default_images['instance2']->fid)
1784
      )
1785
    );
1786
  }
1787

    
1788
}
1789

    
1790
/**
1791
 * Tests image theme functions.
1792
 */
1793
class ImageThemeFunctionWebTestCase extends DrupalWebTestCase {
1794

    
1795
  public static function getInfo() {
1796
    return array(
1797
      'name' => 'Image theme functions',
1798
      'description' => 'Test that the image theme functions work correctly.',
1799
      'group' => 'Image',
1800
    );
1801
  }
1802

    
1803
  function setUp() {
1804
    parent::setUp(array('image'));
1805
  }
1806

    
1807
  /**
1808
   * Tests usage of the image field formatters.
1809
   */
1810
  function testImageFormatterTheme() {
1811
    // Create an image.
1812
    $files = $this->drupalGetTestFiles('image');
1813
    $file = reset($files);
1814
    $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
1815

    
1816
    // Create a style.
1817
    image_style_save(array('name' => 'test', 'label' => 'Test'));
1818
    $url = image_style_url('test', $original_uri);
1819

    
1820
    // Test using theme_image_formatter() without an image title, alt text, or
1821
    // link options.
1822
    $path = $this->randomName();
1823
    $element = array(
1824
      '#theme' => 'image_formatter',
1825
      '#image_style' => 'test',
1826
      '#item' => array(
1827
        'uri' => $original_uri,
1828
      ),
1829
      '#path' => array(
1830
        'path' => $path,
1831
      ),
1832
    );
1833
    $rendered_element = render($element);
1834
    $expected_result = '<a href="' . url($path) . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1835
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders without title, alt, or path options.');
1836

    
1837
    // Link the image to a fragment on the page, and not a full URL.
1838
    $fragment = $this->randomName();
1839
    $element['#path']['path'] = '';
1840
    $element['#path']['options'] = array(
1841
      'external' => TRUE,
1842
      'fragment' => $fragment,
1843
    );
1844
    $rendered_element = render($element);
1845
    $expected_result = '<a href="#' . $fragment . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
1846
    $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders a link fragment.');
1847
  }
1848

    
1849
}
1850

    
1851
/**
1852
 * Tests flushing of image styles.
1853
 */
1854
class ImageStyleFlushTest extends ImageFieldTestCase {
1855

    
1856
  public static function getInfo() {
1857
    return array(
1858
      'name' => 'Image style flushing',
1859
      'description' => 'Tests flushing of image styles.',
1860
      'group' => 'Image',
1861
    );
1862
  }
1863

    
1864
  /**
1865
   * Given an image style and a wrapper, generate an image.
1866
   */
1867
  function createSampleImage($style, $wrapper) {
1868
    static $file;
1869

    
1870
    if (!isset($file)) {
1871
      $files = $this->drupalGetTestFiles('image');
1872
      $file = reset($files);
1873
    }
1874

    
1875
    // Make sure we have an image in our wrapper testing file directory.
1876
    $source_uri = file_unmanaged_copy($file->uri, $wrapper . '://');
1877
    // Build the derivative image.
1878
    $derivative_uri = image_style_path($style['name'], $source_uri);
1879
    $derivative = image_style_create_derivative($style, $source_uri, $derivative_uri);
1880

    
1881
    return $derivative ? $derivative_uri : FALSE;
1882
  }
1883

    
1884
  /**
1885
   * Count the number of images currently created for a style in a wrapper.
1886
   */
1887
  function getImageCount($style, $wrapper) {
1888
    return count(file_scan_directory($wrapper . '://styles/' . $style['name'], '/.*/'));
1889
  }
1890

    
1891
  /**
1892
   * General test to flush a style.
1893
   */
1894
  function testFlush() {
1895

    
1896
    // Setup a style to be created and effects to add to it.
1897
    $style_name = strtolower($this->randomName(10));
1898
    $style_label = $this->randomString();
1899
    $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
1900
    $effect_edits = array(
1901
      'image_resize' => array(
1902
        'data[width]' => 100,
1903
        'data[height]' => 101,
1904
      ),
1905
      'image_scale' => array(
1906
        'data[width]' => 110,
1907
        'data[height]' => 111,
1908
        'data[upscale]' => 1,
1909
      ),
1910
    );
1911

    
1912
    // Add style form.
1913
    $edit = array(
1914
      'name' => $style_name,
1915
      'label' => $style_label,
1916
    );
1917
    $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
1918
    // Add each sample effect to the style.
1919
    foreach ($effect_edits as $effect => $edit) {
1920
      // Add the effect.
1921
      $this->drupalPost($style_path, array('new' => $effect), t('Add'));
1922
      if (!empty($edit)) {
1923
        $this->drupalPost(NULL, $edit, t('Add effect'));
1924
      }
1925
    }
1926

    
1927
    // Load the saved image style.
1928
    $style = image_style_load($style_name);
1929

    
1930
    // Create an image for the 'public' wrapper.
1931
    $image_path = $this->createSampleImage($style, 'public');
1932
    // Expecting to find 2 images, one is the sample.png image shown in
1933
    // image style preview.
1934
    $this->assertEqual($this->getImageCount($style, 'public'), 2, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
1935

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

    
1940
    // Remove the 'image_scale' effect and updates the style, which in turn
1941
    // forces an image style flush.
1942
    $effect = array_pop($style['effects']);
1943
    $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
1944
    $this->assertResponse(200);
1945
    $this->drupalPost($style_path, array(), t('Update style'));
1946
    $this->assertResponse(200);
1947

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

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