image.test 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. <?php
  2. /**
  3. * @file
  4. * Tests for core image handling API.
  5. */
  6. /**
  7. * Base class for image manipulation testing.
  8. */
  9. class ImageToolkitTestCase extends DrupalWebTestCase {
  10. protected $toolkit;
  11. protected $file;
  12. protected $image;
  13. function setUp() {
  14. $modules = func_get_args();
  15. if (isset($modules[0]) && is_array($modules[0])) {
  16. $modules = $modules[0];
  17. }
  18. $modules[] = 'image_test';
  19. parent::setUp($modules);
  20. // Use the image_test.module's test toolkit.
  21. $this->toolkit = 'test';
  22. // Pick a file for testing.
  23. $file = current($this->drupalGetTestFiles('image'));
  24. $this->file = $file->uri;
  25. // Setup a dummy image to work with, this replicate image_load() so we
  26. // can avoid calling it.
  27. $this->image = new stdClass();
  28. $this->image->source = $this->file;
  29. $this->image->info = image_get_info($this->file);
  30. $this->image->toolkit = $this->toolkit;
  31. // Clear out any hook calls.
  32. image_test_reset();
  33. }
  34. /**
  35. * Assert that all of the specified image toolkit operations were called
  36. * exactly once once, other values result in failure.
  37. *
  38. * @param $expected
  39. * Array with string containing with the operation name, e.g. 'load',
  40. * 'save', 'crop', etc.
  41. */
  42. function assertToolkitOperationsCalled(array $expected) {
  43. // Determine which operations were called.
  44. $actual = array_keys(array_filter(image_test_get_all_calls()));
  45. // Determine if there were any expected that were not called.
  46. $uncalled = array_diff($expected, $actual);
  47. if (count($uncalled)) {
  48. $this->assertTrue(FALSE, format_string('Expected operations %expected to be called but %uncalled was not called.', array('%expected' => implode(', ', $expected), '%uncalled' => implode(', ', $uncalled))));
  49. }
  50. else {
  51. $this->assertTrue(TRUE, format_string('All the expected operations were called: %expected', array('%expected' => implode(', ', $expected))));
  52. }
  53. // Determine if there were any unexpected calls.
  54. $unexpected = array_diff($actual, $expected);
  55. if (count($unexpected)) {
  56. $this->assertTrue(FALSE, format_string('Unexpected operations were called: %unexpected.', array('%unexpected' => implode(', ', $unexpected))));
  57. }
  58. else {
  59. $this->assertTrue(TRUE, 'No unexpected operations were called.');
  60. }
  61. }
  62. }
  63. /**
  64. * Test that the functions in image.inc correctly pass data to the toolkit.
  65. */
  66. class ImageToolkitUnitTest extends ImageToolkitTestCase {
  67. public static function getInfo() {
  68. return array(
  69. 'name' => 'Image toolkit tests',
  70. 'description' => 'Check image toolkit functions.',
  71. 'group' => 'Image',
  72. );
  73. }
  74. /**
  75. * Check that hook_image_toolkits() is called and only available toolkits are
  76. * returned.
  77. */
  78. function testGetAvailableToolkits() {
  79. $toolkits = image_get_available_toolkits();
  80. $this->assertTrue(isset($toolkits['test']), 'The working toolkit was returned.');
  81. $this->assertFalse(isset($toolkits['broken']), 'The toolkit marked unavailable was not returned');
  82. $this->assertToolkitOperationsCalled(array());
  83. }
  84. /**
  85. * Test the image_load() function.
  86. */
  87. function testLoad() {
  88. $image = image_load($this->file, $this->toolkit);
  89. $this->assertTrue(is_object($image), 'Returned an object.');
  90. $this->assertEqual($this->toolkit, $image->toolkit, 'Image had toolkit set.');
  91. $this->assertToolkitOperationsCalled(array('load', 'get_info'));
  92. }
  93. /**
  94. * Test the image_save() function.
  95. */
  96. function testSave() {
  97. $this->assertFalse(image_save($this->image), 'Function returned the expected value.');
  98. $this->assertToolkitOperationsCalled(array('save'));
  99. }
  100. /**
  101. * Test the image_resize() function.
  102. */
  103. function testResize() {
  104. $this->assertTrue(image_resize($this->image, 1, 2), 'Function returned the expected value.');
  105. $this->assertToolkitOperationsCalled(array('resize'));
  106. // Check the parameters.
  107. $calls = image_test_get_all_calls();
  108. $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
  109. $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
  110. }
  111. /**
  112. * Test the image_scale() function.
  113. */
  114. function testScale() {
  115. // TODO: need to test upscaling
  116. $this->assertTrue(image_scale($this->image, 10, 10), 'Function returned the expected value.');
  117. $this->assertToolkitOperationsCalled(array('resize'));
  118. // Check the parameters.
  119. $calls = image_test_get_all_calls();
  120. $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
  121. $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
  122. }
  123. /**
  124. * Test the image_scale_and_crop() function.
  125. */
  126. function testScaleAndCrop() {
  127. $this->assertTrue(image_scale_and_crop($this->image, 5, 10), 'Function returned the expected value.');
  128. $this->assertToolkitOperationsCalled(array('resize', 'crop'));
  129. // Check the parameters.
  130. $calls = image_test_get_all_calls();
  131. $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
  132. $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
  133. $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
  134. $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
  135. }
  136. /**
  137. * Test the image_rotate() function.
  138. */
  139. function testRotate() {
  140. $this->assertTrue(image_rotate($this->image, 90, 1), 'Function returned the expected value.');
  141. $this->assertToolkitOperationsCalled(array('rotate'));
  142. // Check the parameters.
  143. $calls = image_test_get_all_calls();
  144. $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
  145. $this->assertEqual($calls['rotate'][0][2], 1, 'Background color was passed correctly');
  146. }
  147. /**
  148. * Test the image_crop() function.
  149. */
  150. function testCrop() {
  151. $this->assertTrue(image_crop($this->image, 1, 2, 3, 4), 'Function returned the expected value.');
  152. $this->assertToolkitOperationsCalled(array('crop'));
  153. // Check the parameters.
  154. $calls = image_test_get_all_calls();
  155. $this->assertEqual($calls['crop'][0][1], 1, 'X was passed correctly');
  156. $this->assertEqual($calls['crop'][0][2], 2, 'Y was passed correctly');
  157. $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
  158. $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
  159. }
  160. /**
  161. * Test the image_desaturate() function.
  162. */
  163. function testDesaturate() {
  164. $this->assertTrue(image_desaturate($this->image), 'Function returned the expected value.');
  165. $this->assertToolkitOperationsCalled(array('desaturate'));
  166. // Check the parameters.
  167. $calls = image_test_get_all_calls();
  168. $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
  169. }
  170. }
  171. /**
  172. * Test the core GD image manipulation functions.
  173. */
  174. class ImageToolkitGdTestCase extends DrupalWebTestCase {
  175. // Colors that are used in testing.
  176. protected $black = array(0, 0, 0, 0);
  177. protected $red = array(255, 0, 0, 0);
  178. protected $green = array(0, 255, 0, 0);
  179. protected $blue = array(0, 0, 255, 0);
  180. protected $yellow = array(255, 255, 0, 0);
  181. protected $white = array(255, 255, 255, 0);
  182. protected $transparent = array(0, 0, 0, 127);
  183. // Used as rotate background colors.
  184. protected $fuchsia = array(255, 0, 255, 0);
  185. protected $rotate_transparent = array(255, 255, 255, 127);
  186. protected $width = 40;
  187. protected $height = 20;
  188. public static function getInfo() {
  189. return array(
  190. 'name' => 'Image GD manipulation tests',
  191. 'description' => 'Check that core image manipulations work properly: scale, resize, rotate, crop, scale and crop, and desaturate.',
  192. 'group' => 'Image',
  193. );
  194. }
  195. /**
  196. * Function to compare two colors by RGBa.
  197. */
  198. function colorsAreEqual($color_a, $color_b) {
  199. // Fully transparent pixels are equal, regardless of RGB.
  200. if ($color_a[3] == 127 && $color_b[3] == 127) {
  201. return TRUE;
  202. }
  203. foreach ($color_a as $key => $value) {
  204. if ($color_b[$key] != $value) {
  205. return FALSE;
  206. }
  207. }
  208. return TRUE;
  209. }
  210. /**
  211. * Function for finding a pixel's RGBa values.
  212. */
  213. function getPixelColor($image, $x, $y) {
  214. $color_index = imagecolorat($image->resource, $x, $y);
  215. $transparent_index = imagecolortransparent($image->resource);
  216. if ($color_index == $transparent_index) {
  217. return array(0, 0, 0, 127);
  218. }
  219. return array_values(imagecolorsforindex($image->resource, $color_index));
  220. }
  221. /**
  222. * Since PHP can't visually check that our images have been manipulated
  223. * properly, build a list of expected color values for each of the corners and
  224. * the expected height and widths for the final images.
  225. */
  226. function testManipulations() {
  227. // If GD isn't available don't bother testing this.
  228. module_load_include('inc', 'system', 'image.gd');
  229. if (!function_exists('image_gd_check_settings') || !image_gd_check_settings()) {
  230. $this->pass(t('Image manipulations for the GD toolkit were skipped because the GD toolkit is not available.'));
  231. return;
  232. }
  233. // Typically the corner colors will be unchanged. These colors are in the
  234. // order of top-left, top-right, bottom-right, bottom-left.
  235. $default_corners = array($this->red, $this->green, $this->blue, $this->transparent);
  236. // A list of files that will be tested.
  237. $files = array(
  238. 'image-test.png',
  239. 'image-test.gif',
  240. 'image-test-no-transparency.gif',
  241. 'image-test.jpg',
  242. );
  243. // Setup a list of tests to perform on each type.
  244. $operations = array(
  245. 'resize' => array(
  246. 'function' => 'resize',
  247. 'arguments' => array(20, 10),
  248. 'width' => 20,
  249. 'height' => 10,
  250. 'corners' => $default_corners,
  251. ),
  252. 'scale_x' => array(
  253. 'function' => 'scale',
  254. 'arguments' => array(20, NULL),
  255. 'width' => 20,
  256. 'height' => 10,
  257. 'corners' => $default_corners,
  258. ),
  259. 'scale_y' => array(
  260. 'function' => 'scale',
  261. 'arguments' => array(NULL, 10),
  262. 'width' => 20,
  263. 'height' => 10,
  264. 'corners' => $default_corners,
  265. ),
  266. 'upscale_x' => array(
  267. 'function' => 'scale',
  268. 'arguments' => array(80, NULL, TRUE),
  269. 'width' => 80,
  270. 'height' => 40,
  271. 'corners' => $default_corners,
  272. ),
  273. 'upscale_y' => array(
  274. 'function' => 'scale',
  275. 'arguments' => array(NULL, 40, TRUE),
  276. 'width' => 80,
  277. 'height' => 40,
  278. 'corners' => $default_corners,
  279. ),
  280. 'crop' => array(
  281. 'function' => 'crop',
  282. 'arguments' => array(12, 4, 16, 12),
  283. 'width' => 16,
  284. 'height' => 12,
  285. 'corners' => array_fill(0, 4, $this->white),
  286. ),
  287. 'scale_and_crop' => array(
  288. 'function' => 'scale_and_crop',
  289. 'arguments' => array(10, 8),
  290. 'width' => 10,
  291. 'height' => 8,
  292. 'corners' => array_fill(0, 4, $this->black),
  293. ),
  294. );
  295. // Systems using non-bundled GD2 don't have imagerotate. Test if available.
  296. // @todo Remove the version check once https://www.drupal.org/node/2918570
  297. // is resolved.
  298. if (function_exists('imagerotate') && (version_compare(PHP_VERSION, '7.0.26', '<') || (version_compare(PHP_VERSION, '7.1', '>=') && version_compare(PHP_VERSION, '7.1.12', '<')))) {
  299. $operations += array(
  300. 'rotate_90' => array(
  301. 'function' => 'rotate',
  302. 'arguments' => array(90, 0xFF00FF), // Fuchsia background.
  303. 'width' => 20,
  304. 'height' => 40,
  305. 'corners' => array($this->fuchsia, $this->red, $this->green, $this->blue),
  306. ),
  307. 'rotate_transparent_90' => array(
  308. 'function' => 'rotate',
  309. 'arguments' => array(90),
  310. 'width' => 20,
  311. 'height' => 40,
  312. 'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
  313. ),
  314. );
  315. // As of PHP version 5.5, GD uses a different algorithm to rotate images
  316. // than version 5.4 and below, resulting in different dimensions.
  317. // See https://bugs.php.net/bug.php?id=65148.
  318. // For the 40x20 test images, the dimensions resulting from rotation will
  319. // be 1 pixel smaller in both width and height in PHP 5.5 and above.
  320. // @todo: The PHP bug was fixed in PHP 7.0.26 and 7.1.12. Change the code
  321. // below to reflect that in https://www.drupal.org/node/2918570.
  322. if (version_compare(PHP_VERSION, '5.5', '>=')) {
  323. $operations += array(
  324. 'rotate_5' => array(
  325. 'function' => 'rotate',
  326. 'arguments' => array(5, 0xFF00FF), // Fuchsia background.
  327. 'width' => 41,
  328. 'height' => 23,
  329. 'corners' => array_fill(0, 4, $this->fuchsia),
  330. ),
  331. 'rotate_transparent_5' => array(
  332. 'function' => 'rotate',
  333. 'arguments' => array(5),
  334. 'width' => 41,
  335. 'height' => 23,
  336. 'corners' => array_fill(0, 4, $this->rotate_transparent),
  337. ),
  338. );
  339. }
  340. else {
  341. $operations += array(
  342. 'rotate_5' => array(
  343. 'function' => 'rotate',
  344. 'arguments' => array(5, 0xFF00FF), // Fuchsia background.
  345. 'width' => 42,
  346. 'height' => 24,
  347. 'corners' => array_fill(0, 4, $this->fuchsia),
  348. ),
  349. 'rotate_transparent_5' => array(
  350. 'function' => 'rotate',
  351. 'arguments' => array(5),
  352. 'width' => 42,
  353. 'height' => 24,
  354. 'corners' => array_fill(0, 4, $this->rotate_transparent),
  355. ),
  356. );
  357. }
  358. }
  359. // Systems using non-bundled GD2 don't have imagefilter. Test if available.
  360. if (function_exists('imagefilter')) {
  361. $operations += array(
  362. 'desaturate' => array(
  363. 'function' => 'desaturate',
  364. 'arguments' => array(),
  365. 'height' => 20,
  366. 'width' => 40,
  367. // Grayscale corners are a bit funky. Each of the corners are a shade of
  368. // gray. The values of these were determined simply by looking at the
  369. // final image to see what desaturated colors end up being.
  370. 'corners' => array(
  371. array_fill(0, 3, 76) + array(3 => 0),
  372. array_fill(0, 3, 149) + array(3 => 0),
  373. array_fill(0, 3, 29) + array(3 => 0),
  374. array_fill(0, 3, 225) + array(3 => 127)
  375. ),
  376. ),
  377. );
  378. }
  379. foreach ($files as $file) {
  380. foreach ($operations as $op => $values) {
  381. // Load up a fresh image.
  382. $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file, 'gd');
  383. if (!$image) {
  384. $this->fail(t('Could not load image %file.', array('%file' => $file)));
  385. continue 2;
  386. }
  387. // All images should be converted to truecolor when loaded.
  388. $image_truecolor = imageistruecolor($image->resource);
  389. $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
  390. if ($image->info['extension'] == 'gif') {
  391. if ($op == 'desaturate') {
  392. // Transparent GIFs and the imagefilter function don't work together.
  393. $values['corners'][3][3] = 0;
  394. }
  395. }
  396. // Perform our operation.
  397. $function = 'image_' . $values['function'];
  398. $arguments = array();
  399. $arguments[] = &$image;
  400. $arguments = array_merge($arguments, $values['arguments']);
  401. call_user_func_array($function, $arguments);
  402. // To keep from flooding the test with assert values, make a general
  403. // value for whether each group of values fail.
  404. $correct_dimensions_real = TRUE;
  405. $correct_dimensions_object = TRUE;
  406. $correct_colors = TRUE;
  407. // Check the real dimensions of the image first.
  408. if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) {
  409. $correct_dimensions_real = FALSE;
  410. }
  411. // Check that the image object has an accurate record of the dimensions.
  412. if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) {
  413. $correct_dimensions_object = FALSE;
  414. }
  415. // Now check each of the corners to ensure color correctness.
  416. foreach ($values['corners'] as $key => $corner) {
  417. // The test gif that does not have transparency has yellow where the
  418. // others have transparent.
  419. if ($file === 'image-test-no-transparency.gif' && $corner === $this->transparent) {
  420. $corner = $this->yellow;
  421. }
  422. // Get the location of the corner.
  423. switch ($key) {
  424. case 0:
  425. $x = 0;
  426. $y = 0;
  427. break;
  428. case 1:
  429. $x = $values['width'] - 1;
  430. $y = 0;
  431. break;
  432. case 2:
  433. $x = $values['width'] - 1;
  434. $y = $values['height'] - 1;
  435. break;
  436. case 3:
  437. $x = 0;
  438. $y = $values['height'] - 1;
  439. break;
  440. }
  441. $color = $this->getPixelColor($image, $x, $y);
  442. $correct_colors = $this->colorsAreEqual($color, $corner);
  443. }
  444. $directory = file_default_scheme() . '://imagetests';
  445. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  446. $file_path = $directory . '/' . $op . '.' . $image->info['extension'];
  447. image_save($image, $file_path);
  448. $this->assertTrue($correct_dimensions_real, format_string('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op)));
  449. $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)));
  450. // JPEG colors will always be messed up due to compression.
  451. if ($image->info['extension'] != 'jpg') {
  452. $this->assertTrue($correct_colors, format_string('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op)));
  453. }
  454. }
  455. // Check that saved image reloads without raising PHP errors.
  456. $image_reloaded = image_load($file_path);
  457. }
  458. }
  459. /**
  460. * Tests loading an image whose transparent color index is out of range.
  461. */
  462. function testTransparentColorOutOfRange() {
  463. // This image was generated by taking an initial image with a palette size
  464. // of 6 colors, and setting the transparent color index to 6 (one higher
  465. // than the largest allowed index), as follows:
  466. // @code
  467. // $image = imagecreatefromgif('modules/simpletest/files/image-test.gif');
  468. // imagecolortransparent($image, 6);
  469. // imagegif($image, 'modules/simpletest/files/image-test-transparent-out-of-range.gif');
  470. // @endcode
  471. // This allows us to test that an image with an out-of-range color index
  472. // can be loaded correctly.
  473. $file = 'image-test-transparent-out-of-range.gif';
  474. $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file);
  475. if (!$image) {
  476. $this->fail(format_string('Could not load image %file.', array('%file' => $file)));
  477. }
  478. else {
  479. // All images should be converted to truecolor when loaded.
  480. $image_truecolor = imageistruecolor($image->resource);
  481. $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
  482. }
  483. }
  484. }
  485. /**
  486. * Tests the file move function for managed files.
  487. */
  488. class ImageFileMoveTest extends ImageToolkitTestCase {
  489. public static function getInfo() {
  490. return array(
  491. 'name' => 'Image moving',
  492. 'description' => 'Tests the file move function for managed files.',
  493. 'group' => 'Image',
  494. );
  495. }
  496. /**
  497. * Tests moving a randomly generated image.
  498. */
  499. function testNormal() {
  500. // Pick a file for testing.
  501. $file = current($this->drupalGetTestFiles('image'));
  502. // Create derivative image.
  503. $style = image_style_load(key(image_styles()));
  504. $derivative_uri = image_style_path($style['name'], $file->uri);
  505. image_style_create_derivative($style, $file->uri, $derivative_uri);
  506. // Check if derivative image exists.
  507. $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');
  508. // Clone the object so we don't have to worry about the function changing
  509. // our reference copy.
  510. $desired_filepath = 'public://' . $this->randomName();
  511. $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
  512. // Check if image has been moved.
  513. $this->assertTrue(file_exists($result->uri), 'Make sure image is moved successfully.');
  514. // Check if derivative image has been flushed.
  515. $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
  516. }
  517. }