image.test 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. if (function_exists('imagerotate')) {
  297. $operations += array(
  298. 'rotate_90' => array(
  299. 'function' => 'rotate',
  300. 'arguments' => array(90, 0xFF00FF), // Fuchsia background.
  301. 'width' => 20,
  302. 'height' => 40,
  303. 'corners' => array($this->fuchsia, $this->red, $this->green, $this->blue),
  304. ),
  305. 'rotate_transparent_90' => array(
  306. 'function' => 'rotate',
  307. 'arguments' => array(90),
  308. 'width' => 20,
  309. 'height' => 40,
  310. 'corners' => array($this->transparent, $this->red, $this->green, $this->blue),
  311. ),
  312. );
  313. // As of PHP version 5.5, GD uses a different algorithm to rotate images
  314. // than version 5.4 and below, resulting in different dimensions.
  315. // See https://bugs.php.net/bug.php?id=65148.
  316. // For the 40x20 test images, the dimensions resulting from rotation will
  317. // be 1 pixel smaller in both width and height in PHP 5.5 and above.
  318. // @todo: If and when the PHP bug gets solved, add an upper limit
  319. // version check.
  320. if (version_compare(PHP_VERSION, '5.5', '>=')) {
  321. $operations += array(
  322. 'rotate_5' => array(
  323. 'function' => 'rotate',
  324. 'arguments' => array(5, 0xFF00FF), // Fuchsia background.
  325. 'width' => 41,
  326. 'height' => 23,
  327. 'corners' => array_fill(0, 4, $this->fuchsia),
  328. ),
  329. 'rotate_transparent_5' => array(
  330. 'function' => 'rotate',
  331. 'arguments' => array(5),
  332. 'width' => 41,
  333. 'height' => 23,
  334. 'corners' => array_fill(0, 4, $this->rotate_transparent),
  335. ),
  336. );
  337. }
  338. else {
  339. $operations += array(
  340. 'rotate_5' => array(
  341. 'function' => 'rotate',
  342. 'arguments' => array(5, 0xFF00FF), // Fuchsia background.
  343. 'width' => 42,
  344. 'height' => 24,
  345. 'corners' => array_fill(0, 4, $this->fuchsia),
  346. ),
  347. 'rotate_transparent_5' => array(
  348. 'function' => 'rotate',
  349. 'arguments' => array(5),
  350. 'width' => 42,
  351. 'height' => 24,
  352. 'corners' => array_fill(0, 4, $this->rotate_transparent),
  353. ),
  354. );
  355. }
  356. }
  357. // Systems using non-bundled GD2 don't have imagefilter. Test if available.
  358. if (function_exists('imagefilter')) {
  359. $operations += array(
  360. 'desaturate' => array(
  361. 'function' => 'desaturate',
  362. 'arguments' => array(),
  363. 'height' => 20,
  364. 'width' => 40,
  365. // Grayscale corners are a bit funky. Each of the corners are a shade of
  366. // gray. The values of these were determined simply by looking at the
  367. // final image to see what desaturated colors end up being.
  368. 'corners' => array(
  369. array_fill(0, 3, 76) + array(3 => 0),
  370. array_fill(0, 3, 149) + array(3 => 0),
  371. array_fill(0, 3, 29) + array(3 => 0),
  372. array_fill(0, 3, 225) + array(3 => 127)
  373. ),
  374. ),
  375. );
  376. }
  377. foreach ($files as $file) {
  378. foreach ($operations as $op => $values) {
  379. // Load up a fresh image.
  380. $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file, 'gd');
  381. if (!$image) {
  382. $this->fail(t('Could not load image %file.', array('%file' => $file)));
  383. continue 2;
  384. }
  385. // All images should be converted to truecolor when loaded.
  386. $image_truecolor = imageistruecolor($image->resource);
  387. $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
  388. if ($image->info['extension'] == 'gif') {
  389. if ($op == 'desaturate') {
  390. // Transparent GIFs and the imagefilter function don't work together.
  391. $values['corners'][3][3] = 0;
  392. }
  393. }
  394. // Perform our operation.
  395. $function = 'image_' . $values['function'];
  396. $arguments = array();
  397. $arguments[] = &$image;
  398. $arguments = array_merge($arguments, $values['arguments']);
  399. call_user_func_array($function, $arguments);
  400. // To keep from flooding the test with assert values, make a general
  401. // value for whether each group of values fail.
  402. $correct_dimensions_real = TRUE;
  403. $correct_dimensions_object = TRUE;
  404. $correct_colors = TRUE;
  405. // Check the real dimensions of the image first.
  406. if (imagesy($image->resource) != $values['height'] || imagesx($image->resource) != $values['width']) {
  407. $correct_dimensions_real = FALSE;
  408. }
  409. // Check that the image object has an accurate record of the dimensions.
  410. if ($image->info['width'] != $values['width'] || $image->info['height'] != $values['height']) {
  411. $correct_dimensions_object = FALSE;
  412. }
  413. // Now check each of the corners to ensure color correctness.
  414. foreach ($values['corners'] as $key => $corner) {
  415. // The test gif that does not have transparency has yellow where the
  416. // others have transparent.
  417. if ($file === 'image-test-no-transparency.gif' && $corner === $this->transparent) {
  418. $corner = $this->yellow;
  419. }
  420. // Get the location of the corner.
  421. switch ($key) {
  422. case 0:
  423. $x = 0;
  424. $y = 0;
  425. break;
  426. case 1:
  427. $x = $values['width'] - 1;
  428. $y = 0;
  429. break;
  430. case 2:
  431. $x = $values['width'] - 1;
  432. $y = $values['height'] - 1;
  433. break;
  434. case 3:
  435. $x = 0;
  436. $y = $values['height'] - 1;
  437. break;
  438. }
  439. $color = $this->getPixelColor($image, $x, $y);
  440. $correct_colors = $this->colorsAreEqual($color, $corner);
  441. }
  442. $directory = file_default_scheme() . '://imagetests';
  443. file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  444. $file_path = $directory . '/' . $op . '.' . $image->info['extension'];
  445. image_save($image, $file_path);
  446. $this->assertTrue($correct_dimensions_real, format_string('Image %file after %action action has proper dimensions.', array('%file' => $file, '%action' => $op)));
  447. $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)));
  448. // JPEG colors will always be messed up due to compression.
  449. if ($image->info['extension'] != 'jpg') {
  450. $this->assertTrue($correct_colors, format_string('Image %file object after %action action has the correct color placement.', array('%file' => $file, '%action' => $op)));
  451. }
  452. }
  453. // Check that saved image reloads without raising PHP errors.
  454. $image_reloaded = image_load($file_path);
  455. }
  456. }
  457. /**
  458. * Tests loading an image whose transparent color index is out of range.
  459. */
  460. function testTransparentColorOutOfRange() {
  461. // This image was generated by taking an initial image with a palette size
  462. // of 6 colors, and setting the transparent color index to 6 (one higher
  463. // than the largest allowed index), as follows:
  464. // @code
  465. // $image = imagecreatefromgif('modules/simpletest/files/image-test.gif');
  466. // imagecolortransparent($image, 6);
  467. // imagegif($image, 'modules/simpletest/files/image-test-transparent-out-of-range.gif');
  468. // @endcode
  469. // This allows us to test that an image with an out-of-range color index
  470. // can be loaded correctly.
  471. $file = 'image-test-transparent-out-of-range.gif';
  472. $image = image_load(drupal_get_path('module', 'simpletest') . '/files/' . $file);
  473. if (!$image) {
  474. $this->fail(format_string('Could not load image %file.', array('%file' => $file)));
  475. }
  476. else {
  477. // All images should be converted to truecolor when loaded.
  478. $image_truecolor = imageistruecolor($image->resource);
  479. $this->assertTrue($image_truecolor, format_string('Image %file after load is a truecolor image.', array('%file' => $file)));
  480. }
  481. }
  482. }
  483. /**
  484. * Tests the file move function for managed files.
  485. */
  486. class ImageFileMoveTest extends ImageToolkitTestCase {
  487. public static function getInfo() {
  488. return array(
  489. 'name' => 'Image moving',
  490. 'description' => 'Tests the file move function for managed files.',
  491. 'group' => 'Image',
  492. );
  493. }
  494. /**
  495. * Tests moving a randomly generated image.
  496. */
  497. function testNormal() {
  498. // Pick a file for testing.
  499. $file = current($this->drupalGetTestFiles('image'));
  500. // Create derivative image.
  501. $style = image_style_load(key(image_styles()));
  502. $derivative_uri = image_style_path($style['name'], $file->uri);
  503. image_style_create_derivative($style, $file->uri, $derivative_uri);
  504. // Check if derivative image exists.
  505. $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');
  506. // Clone the object so we don't have to worry about the function changing
  507. // our reference copy.
  508. $desired_filepath = 'public://' . $this->randomName();
  509. $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
  510. // Check if image has been moved.
  511. $this->assertTrue(file_exists($result->uri), 'Make sure image is moved successfully.');
  512. // Check if derivative image has been flushed.
  513. $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
  514. }
  515. }