Projet

Général

Profil

Paste
Télécharger (20,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / simpletest / tests / image.test @ cd5c298a

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for core image handling API.
6
 */
7

    
8
/**
9
 * Base class for image manipulation testing.
10
 */
11
class ImageToolkitTestCase extends DrupalWebTestCase {
12
  protected $toolkit;
13
  protected $file;
14
  protected $image;
15

    
16
  function setUp() {
17
    $modules = func_get_args();
18
    if (isset($modules[0]) && is_array($modules[0])) {
19
      $modules = $modules[0];
20
    }
21
    $modules[] = 'image_test';
22

    
23
    parent::setUp($modules);
24

    
25
    // Use the image_test.module's test toolkit.
26
    $this->toolkit = 'test';
27

    
28
    // Pick a file for testing.
29
    $file = current($this->drupalGetTestFiles('image'));
30
    $this->file = $file->uri;
31

    
32
    // Setup a dummy image to work with, this replicate image_load() so we
33
    // can avoid calling it.
34
    $this->image = new stdClass();
35
    $this->image->source = $this->file;
36
    $this->image->info = image_get_info($this->file);
37
    $this->image->toolkit = $this->toolkit;
38

    
39
    // Clear out any hook calls.
40
    image_test_reset();
41
  }
42

    
43
  /**
44
   * Assert that all of the specified image toolkit operations were called
45
   * exactly once once, other values result in failure.
46
   *
47
   * @param $expected
48
   *   Array with string containing with the operation name, e.g. 'load',
49
   *   'save', 'crop', etc.
50
   */
51
  function assertToolkitOperationsCalled(array $expected) {
52
    // Determine which operations were called.
53
    $actual = array_keys(array_filter(image_test_get_all_calls()));
54

    
55
    // Determine if there were any expected that were not called.
56
    $uncalled = array_diff($expected, $actual);
57
    if (count($uncalled)) {
58
      $this->assertTrue(FALSE, format_string('Expected operations %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
59
    }
60
    else {
61
      $this->assertTrue(TRUE, format_string('All the expected operations were called: %expected', array('%expected' => implode(', ', $expected))));
62
    }
63

    
64
    // Determine if there were any unexpected calls.
65
    $unexpected = array_diff($actual, $expected);
66
    if (count($unexpected)) {
67
      $this->assertTrue(FALSE, format_string('Unexpected operations were called: %unexpected.', array('%unexpected' => implode(', ', $unexpected))));
68
    }
69
    else {
70
      $this->assertTrue(TRUE, 'No unexpected operations were called.');
71
    }
72
  }
73
}
74

    
75
/**
76
 * Test that the functions in image.inc correctly pass data to the toolkit.
77
 */
78
class ImageToolkitUnitTest extends ImageToolkitTestCase {
79
  public static function getInfo() {
80
    return array(
81
      'name' => 'Image toolkit tests',
82
      'description' => 'Check image toolkit functions.',
83
      'group' => 'Image',
84
    );
85
  }
86

    
87
  /**
88
   * Check that hook_image_toolkits() is called and only available toolkits are
89
   * returned.
90
   */
91
  function testGetAvailableToolkits() {
92
    $toolkits = image_get_available_toolkits();
93
    $this->assertTrue(isset($toolkits['test']), 'The working toolkit was returned.');
94
    $this->assertFalse(isset($toolkits['broken']), 'The toolkit marked unavailable was not returned');
95
    $this->assertToolkitOperationsCalled(array());
96
  }
97

    
98
  /**
99
   * Test the image_load() function.
100
   */
101
  function testLoad() {
102
    $image = image_load($this->file, $this->toolkit);
103
    $this->assertTrue(is_object($image), 'Returned an object.');
104
    $this->assertEqual($this->toolkit, $image->toolkit, 'Image had toolkit set.');
105
    $this->assertToolkitOperationsCalled(array('load', 'get_info'));
106
  }
107

    
108
  /**
109
   * Test the image_save() function.
110
   */
111
  function testSave() {
112
    $this->assertFalse(image_save($this->image), 'Function returned the expected value.');
113
    $this->assertToolkitOperationsCalled(array('save'));
114
  }
115

    
116
  /**
117
   * Test the image_resize() function.
118
   */
119
  function testResize() {
120
    $this->assertTrue(image_resize($this->image, 1, 2), 'Function returned the expected value.');
121
    $this->assertToolkitOperationsCalled(array('resize'));
122

    
123
    // Check the parameters.
124
    $calls = image_test_get_all_calls();
125
    $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
126
    $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
127
  }
128

    
129
  /**
130
   * Test the image_scale() function.
131
   */
132
  function testScale() {
133
// TODO: need to test upscaling
134
    $this->assertTrue(image_scale($this->image, 10, 10), 'Function returned the expected value.');
135
    $this->assertToolkitOperationsCalled(array('resize'));
136

    
137
    // Check the parameters.
138
    $calls = image_test_get_all_calls();
139
    $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
140
    $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
141
  }
142

    
143
  /**
144
   * Test the image_scale_and_crop() function.
145
   */
146
  function testScaleAndCrop() {
147
    $this->assertTrue(image_scale_and_crop($this->image, 5, 10), 'Function returned the expected value.');
148
    $this->assertToolkitOperationsCalled(array('resize', 'crop'));
149

    
150
    // Check the parameters.
151
    $calls = image_test_get_all_calls();
152

    
153
    $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
154
    $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
155
    $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
156
    $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
157
  }
158

    
159
  /**
160
   * Test the image_rotate() function.
161
   */
162
  function testRotate() {
163
    $this->assertTrue(image_rotate($this->image, 90, 1), 'Function returned the expected value.');
164
    $this->assertToolkitOperationsCalled(array('rotate'));
165

    
166
    // Check the parameters.
167
    $calls = image_test_get_all_calls();
168
    $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
169
    $this->assertEqual($calls['rotate'][0][2], 1, 'Background color was passed correctly');
170
  }
171

    
172
  /**
173
   * Test the image_crop() function.
174
   */
175
  function testCrop() {
176
    $this->assertTrue(image_crop($this->image, 1, 2, 3, 4), 'Function returned the expected value.');
177
    $this->assertToolkitOperationsCalled(array('crop'));
178

    
179
    // Check the parameters.
180
    $calls = image_test_get_all_calls();
181
    $this->assertEqual($calls['crop'][0][1], 1, 'X was passed correctly');
182
    $this->assertEqual($calls['crop'][0][2], 2, 'Y was passed correctly');
183
    $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
184
    $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
185
  }
186

    
187
  /**
188
   * Test the image_desaturate() function.
189
   */
190
  function testDesaturate() {
191
    $this->assertTrue(image_desaturate($this->image), 'Function returned the expected value.');
192
    $this->assertToolkitOperationsCalled(array('desaturate'));
193

    
194
    // Check the parameters.
195
    $calls = image_test_get_all_calls();
196
    $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
197
  }
198
}
199

    
200
/**
201
 * Test the core GD image manipulation functions.
202
 */
203
class ImageToolkitGdTestCase extends DrupalWebTestCase {
204
  // Colors that are used in testing.
205
  protected $black       = array(0, 0, 0, 0);
206
  protected $red         = array(255, 0, 0, 0);
207
  protected $green       = array(0, 255, 0, 0);
208
  protected $blue        = array(0, 0, 255, 0);
209
  protected $yellow      = array(255, 255, 0, 0);
210
  protected $white       = array(255, 255, 255, 0);
211
  protected $transparent = array(0, 0, 0, 127);
212
  // Used as rotate background colors.
213
  protected $fuchsia            = array(255, 0, 255, 0);
214
  protected $rotate_transparent = array(255, 255, 255, 127);
215

    
216
  protected $width = 40;
217
  protected $height = 20;
218

    
219
  public static function getInfo() {
220
    return array(
221
      'name' => 'Image GD manipulation tests',
222
      'description' => 'Check that core image manipulations work properly: scale, resize, rotate, crop, scale and crop, and desaturate.',
223
      'group' => 'Image',
224
    );
225
  }
226

    
227
  /**
228
   * Function to compare two colors by RGBa.
229
   */
230
  function colorsAreEqual($color_a, $color_b) {
231
    // Fully transparent pixels are equal, regardless of RGB.
232
    if ($color_a[3] == 127 && $color_b[3] == 127) {
233
      return TRUE;
234
    }
235

    
236
    foreach ($color_a as $key => $value) {
237
      if ($color_b[$key] != $value) {
238
        return FALSE;
239
      }
240
    }
241

    
242
    return TRUE;
243
  }
244

    
245
  /**
246
   * Function for finding a pixel's RGBa values.
247
   */
248
  function getPixelColor($image, $x, $y) {
249
    $color_index = imagecolorat($image->resource, $x, $y);
250

    
251
    $transparent_index = imagecolortransparent($image->resource);
252
    if ($color_index == $transparent_index) {
253
      return array(0, 0, 0, 127);
254
    }
255

    
256
    return array_values(imagecolorsforindex($image->resource, $color_index));
257
  }
258

    
259
  /**
260
   * Since PHP can't visually check that our images have been manipulated
261
   * properly, build a list of expected color values for each of the corners and
262
   * the expected height and widths for the final images.
263
   */
264
  function testManipulations() {
265
    // If GD isn't available don't bother testing this.
266
    module_load_include('inc', 'system', 'image.gd');
267
    if (!function_exists('image_gd_check_settings') || !image_gd_check_settings()) {
268
      $this->pass(t('Image manipulations for the GD toolkit were skipped because the GD toolkit is not available.'));
269
      return;
270
    }
271

    
272
    // Typically the corner colors will be unchanged. These colors are in the
273
    // order of top-left, top-right, bottom-right, bottom-left.
274
    $default_corners = array($this->red, $this->green, $this->blue, $this->transparent);
275

    
276
    // A list of files that will be tested.
277
    $files = array(
278
      'image-test.png',
279
      'image-test.gif',
280
      'image-test-no-transparency.gif',
281
      'image-test.jpg',
282
    );
283

    
284
    // Setup a list of tests to perform on each type.
285
    $operations = array(
286
      'resize' => array(
287
        'function' => 'resize',
288
        'arguments' => array(20, 10),
289
        'width' => 20,
290
        'height' => 10,
291
        'corners' => $default_corners,
292
      ),
293
      'scale_x' => array(
294
        'function' => 'scale',
295
        'arguments' => array(20, NULL),
296
        'width' => 20,
297
        'height' => 10,
298
        'corners' => $default_corners,
299
      ),
300
      'scale_y' => array(
301
        'function' => 'scale',
302
        'arguments' => array(NULL, 10),
303
        'width' => 20,
304
        'height' => 10,
305
        'corners' => $default_corners,
306
      ),
307
      'upscale_x' => array(
308
        'function' => 'scale',
309
        'arguments' => array(80, NULL, TRUE),
310
        'width' => 80,
311
        'height' => 40,
312
        'corners' => $default_corners,
313
      ),
314
      'upscale_y' => array(
315
        'function' => 'scale',
316
        'arguments' => array(NULL, 40, TRUE),
317
        'width' => 80,
318
        'height' => 40,
319
        'corners' => $default_corners,
320
      ),
321
      'crop' => array(
322
        'function' => 'crop',
323
        'arguments' => array(12, 4, 16, 12),
324
        'width' => 16,
325
        'height' => 12,
326
        'corners' => array_fill(0, 4, $this->white),
327
      ),
328
      'scale_and_crop' => array(
329
        'function' => 'scale_and_crop',
330
        'arguments' => array(10, 8),
331
        'width' => 10,
332
        'height' => 8,
333
        'corners' => array_fill(0, 4, $this->black),
334
      ),
335
    );
336

    
337
    // Systems using non-bundled GD2 don't have imagerotate. Test if available.
338
    // @todo Remove the version check once https://www.drupal.org/node/2918570
339
    //   is resolved.
340
    if (function_exists('imagerotate') && (version_compare(PHP_VERSION, '7.0.26', '<') || (version_compare(PHP_VERSION, '7.1', '>=') && version_compare(PHP_VERSION, '7.1.12', '<')))) {
341
      $operations += array(
342
        'rotate_90' => array(
343
          'function' => 'rotate',
344
          'arguments' => array(90, 0xFF00FF), // Fuchsia background.
345
          'width' => 20,
346
          'height' => 40,
347
          'corners' => array($this->fuchsia, $this->red, $this->green, $this->blue),
348
        ),
349
        'rotate_transparent_90' => array(
350
          'function' => 'rotate',
351
          'arguments' => array(90),
352
          'width' => 20,
353
          'height' => 40,
354
          'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
355
        ),
356
      );
357
      // As of PHP version 5.5, GD uses a different algorithm to rotate images
358
      // than version 5.4 and below, resulting in different dimensions.
359
      // See https://bugs.php.net/bug.php?id=65148.
360
      // For the 40x20 test images, the dimensions resulting from rotation will
361
      // be 1 pixel smaller in both width and height in PHP 5.5 and above.
362
      // @todo: The PHP bug was fixed in PHP 7.0.26 and 7.1.12. Change the code
363
      //   below to reflect that in https://www.drupal.org/node/2918570.
364
      if (version_compare(PHP_VERSION, '5.5', '>=')) {
365
        $operations += array(
366
          'rotate_5' => array(
367
            'function' => 'rotate',
368
            'arguments' => array(5, 0xFF00FF), // Fuchsia background.
369
            'width' => 41,
370
            'height' => 23,
371
            'corners' => array_fill(0, 4, $this->fuchsia),
372
          ),
373
          'rotate_transparent_5' => array(
374
            'function' => 'rotate',
375
            'arguments' => array(5),
376
            'width' => 41,
377
            'height' => 23,
378
            'corners' => array_fill(0, 4, $this->rotate_transparent),
379
          ),
380
        );
381
      }
382
      else {
383
        $operations += array(
384
          'rotate_5' => array(
385
            'function' => 'rotate',
386
            'arguments' => array(5, 0xFF00FF), // Fuchsia background.
387
            'width' => 42,
388
            'height' => 24,
389
            'corners' => array_fill(0, 4, $this->fuchsia),
390
          ),
391
          'rotate_transparent_5' => array(
392
            'function' => 'rotate',
393
            'arguments' => array(5),
394
            'width' => 42,
395
            'height' => 24,
396
            'corners' => array_fill(0, 4, $this->rotate_transparent),
397
          ),
398
        );
399
      }
400
    }
401

    
402
    // Systems using non-bundled GD2 don't have imagefilter. Test if available.
403
    if (function_exists('imagefilter')) {
404
      $operations += array(
405
        'desaturate' => array(
406
          'function' => 'desaturate',
407
          'arguments' => array(),
408
          'height' => 20,
409
          'width' => 40,
410
          // Grayscale corners are a bit funky. Each of the corners are a shade of
411
          // gray. The values of these were determined simply by looking at the
412
          // final image to see what desaturated colors end up being.
413
          'corners' => array(
414
            array_fill(0, 3, 76) + array(3 => 0),
415
            array_fill(0, 3, 149) + array(3 => 0),
416
            array_fill(0, 3, 29) + array(3 => 0),
417
            array_fill(0, 3, 225) + array(3 => 127)
418
          ),
419
        ),
420
      );
421
    }
422

    
423
    foreach ($files as $file) {
424
      foreach ($operations as $op => $values) {
425
        // Load up a fresh image.
426
        $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file, 'gd');
427
        if (!$image) {
428
          $this->fail(t('Could not load image %file.', array('%file' => $file)));
429
          continue 2;
430
        }
431

    
432
        // All images should be converted to truecolor when loaded.
433
        $image_truecolor = imageistruecolor($image->resource);
434
        $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
435

    
436
        if ($image->info['extension'] == 'gif') {
437
          if ($op == 'desaturate') {
438
            // Transparent GIFs and the imagefilter function don't work together.
439
            $values['corners'][3][3] = 0;
440
          }
441
        }
442

    
443
        // Perform our operation.
444
        $function = 'image_' . $values['function'];
445
        $arguments = array();
446
        $arguments[] = &$image;
447
        $arguments = array_merge($arguments, $values['arguments']);
448
        call_user_func_array($function, $arguments);
449

    
450
        // To keep from flooding the test with assert values, make a general
451
        // value for whether each group of values fail.
452
        $correct_dimensions_real = TRUE;
453
        $correct_dimensions_object = TRUE;
454
        $correct_colors = TRUE;
455

    
456
        // Check the real dimensions of the image first.
457
        if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) {
458
          $correct_dimensions_real = FALSE;
459
        }
460

    
461
        // Check that the image object has an accurate record of the dimensions.
462
        if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) {
463
          $correct_dimensions_object = FALSE;
464
        }
465
        // Now check each of the corners to ensure color correctness.
466
        foreach ($values['corners'] as $key => $corner) {
467
          // The test gif that does not have transparency has yellow where the
468
          // others have transparent.
469
          if ($file === 'image-test-no-transparency.gif' && $corner === $this->transparent) {
470
            $corner = $this->yellow;
471
          }
472
          // Get the location of the corner.
473
          switch ($key) {
474
            case 0:
475
              $x = 0;
476
              $y = 0;
477
              break;
478
            case 1:
479
              $x = $values['width'] - 1;
480
              $y = 0;
481
              break;
482
            case 2:
483
              $x = $values['width'] - 1;
484
              $y = $values['height'] - 1;
485
              break;
486
            case 3:
487
              $x = 0;
488
              $y = $values['height'] - 1;
489
              break;
490
          }
491
          $color = $this->getPixelColor($image, $x, $y);
492
          $correct_colors = $this->colorsAreEqual($color, $corner);
493
        }
494

    
495
        $directory = file_default_scheme() . '://imagetests';
496
        file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
497
        $file_path = $directory . '/' . $op . '.' . $image->info['extension'];
498
        image_save($image, $file_path);
499

    
500
        $this->assertTrue($correct_dimensions_real, format_string('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op)));
501
        $this->assertTrue($correct_dimensions_object, format_string('Image %file object after %action action is reporting the proper height and width values.', array('%file' => $file, '%action' => $op)));
502
        // JPEG colors will always be messed up due to compression.
503
        if ($image->info['extension'] != 'jpg') {
504
          $this->assertTrue($correct_colors, format_string('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op)));
505
        }
506
      }
507

    
508
      // Check that saved image reloads without raising PHP errors.
509
      $image_reloaded = image_load($file_path);
510
    }
511
  }
512

    
513
  /**
514
   * Tests loading an image whose transparent color index is out of range.
515
   */
516
  function testTransparentColorOutOfRange() {
517
    // This image was generated by taking an initial image with a palette size
518
    // of 6 colors, and setting the transparent color index to 6 (one higher
519
    // than the largest allowed index), as follows:
520
    // @code
521
    // $image = imagecreatefromgif('modules/simpletest/files/image-test.gif');
522
    // imagecolortransparent($image, 6);
523
    // imagegif($image, 'modules/simpletest/files/image-test-transparent-out-of-range.gif');
524
    // @endcode
525
    // This allows us to test that an image with an out-of-range color index
526
    // can be loaded correctly.
527
    $file = 'image-test-transparent-out-of-range.gif';
528
    $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file);
529

    
530
    if (!$image) {
531
      $this->fail(format_string('Could not load image %file.', array('%file' => $file)));
532
    }
533
    else {
534
      // All images should be converted to truecolor when loaded.
535
      $image_truecolor = imageistruecolor($image->resource);
536
      $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
537
    }
538
  }
539
}
540

    
541
/**
542
 * Tests the file move function for managed files.
543
 */
544
class ImageFileMoveTest extends ImageToolkitTestCase {
545
  public static function getInfo() {
546
    return array(
547
      'name' => 'Image moving',
548
      'description' => 'Tests the file move function for managed files.',
549
      'group' => 'Image',
550
    );
551
  }
552

    
553
  /**
554
   * Tests moving a randomly generated image.
555
   */
556
  function testNormal() {
557
    // Pick a file for testing.
558
    $file = current($this->drupalGetTestFiles('image'));
559

    
560
    // Create derivative image.
561
    $style = image_style_load(key(image_styles()));
562
    $derivative_uri = image_style_path($style['name'], $file->uri);
563
    image_style_create_derivative($style, $file->uri, $derivative_uri);
564

    
565
    // Check if derivative image exists.
566
    $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');
567

    
568
    // Clone the object so we don't have to worry about the function changing
569
    // our reference copy.
570
    $desired_filepath = 'public://' . $this->randomName();
571
    $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
572

    
573
    // Check if image has been moved.
574
    $this->assertTrue(file_exists($result->uri), 'Make sure image is moved successfully.');
575

    
576
    // Check if derivative image has been flushed.
577
    $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
578
  }
579
}
580