image.test 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. <?php
  2. /**
  3. * @file
  4. * Tests for image.module.
  5. */
  6. /**
  7. * TODO: Test the following functions.
  8. *
  9. * image.effects.inc:
  10. * image_style_generate()
  11. * image_style_create_derivative()
  12. *
  13. * image.module:
  14. * image_style_load()
  15. * image_style_save()
  16. * image_style_delete()
  17. * image_style_options()
  18. * image_effect_definition_load()
  19. * image_effect_load()
  20. * image_effect_save()
  21. * image_effect_delete()
  22. * image_filter_keyword()
  23. */
  24. /**
  25. * This class provides methods specifically for testing Image's field handling.
  26. */
  27. class ImageFieldTestCase extends DrupalWebTestCase {
  28. protected $admin_user;
  29. function setUp() {
  30. parent::setUp('image');
  31. $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'));
  32. $this->drupalLogin($this->admin_user);
  33. }
  34. /**
  35. * Create a new image field.
  36. *
  37. * @param $name
  38. * The name of the new field (all lowercase), exclude the "field_" prefix.
  39. * @param $type_name
  40. * The node type that this field will be added to.
  41. * @param $field_settings
  42. * A list of field settings that will be added to the defaults.
  43. * @param $instance_settings
  44. * A list of instance settings that will be added to the instance defaults.
  45. * @param $widget_settings
  46. * A list of widget settings that will be added to the widget defaults.
  47. */
  48. function createImageField($name, $type_name, $field_settings = array(), $instance_settings = array(), $widget_settings = array()) {
  49. $field = array(
  50. 'field_name' => $name,
  51. 'type' => 'image',
  52. 'settings' => array(),
  53. 'cardinality' => !empty($field_settings['cardinality']) ? $field_settings['cardinality'] : 1,
  54. );
  55. $field['settings'] = array_merge($field['settings'], $field_settings);
  56. field_create_field($field);
  57. $instance = array(
  58. 'field_name' => $field['field_name'],
  59. 'entity_type' => 'node',
  60. 'label' => $name,
  61. 'bundle' => $type_name,
  62. 'required' => !empty($instance_settings['required']),
  63. 'settings' => array(),
  64. 'widget' => array(
  65. 'type' => 'image_image',
  66. 'settings' => array(),
  67. ),
  68. );
  69. $instance['settings'] = array_merge($instance['settings'], $instance_settings);
  70. $instance['widget']['settings'] = array_merge($instance['widget']['settings'], $widget_settings);
  71. return field_create_instance($instance);
  72. }
  73. /**
  74. * Upload an image to a node.
  75. *
  76. * @param $image
  77. * A file object representing the image to upload.
  78. * @param $field_name
  79. * Name of the image field the image should be attached to.
  80. * @param $type
  81. * The type of node to create.
  82. */
  83. function uploadNodeImage($image, $field_name, $type) {
  84. $edit = array(
  85. 'title' => $this->randomName(),
  86. );
  87. $edit['files[' . $field_name . '_' . LANGUAGE_NONE . '_0]'] = drupal_realpath($image->uri);
  88. $this->drupalPost('node/add/' . $type, $edit, t('Save'));
  89. // Retrieve ID of the newly created node from the current URL.
  90. $matches = array();
  91. preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
  92. return isset($matches[1]) ? $matches[1] : FALSE;
  93. }
  94. }
  95. /**
  96. * Tests the functions for generating paths and URLs for image styles.
  97. */
  98. class ImageStylesPathAndUrlTestCase extends DrupalWebTestCase {
  99. protected $style_name;
  100. protected $image_info;
  101. protected $image_filepath;
  102. public static function getInfo() {
  103. return array(
  104. 'name' => 'Image styles path and URL functions',
  105. 'description' => 'Tests functions for generating paths and URLs to image styles.',
  106. 'group' => 'Image',
  107. );
  108. }
  109. function setUp() {
  110. parent::setUp('image_module_test');
  111. $this->style_name = 'style_foo';
  112. image_style_save(array('name' => $this->style_name, 'label' => $this->randomString()));
  113. }
  114. /**
  115. * Test image_style_path().
  116. */
  117. function testImageStylePath() {
  118. $scheme = 'public';
  119. $actual = image_style_path($this->style_name, "$scheme://foo/bar.gif");
  120. $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
  121. $this->assertEqual($actual, $expected, 'Got the path for a file URI.');
  122. $actual = image_style_path($this->style_name, 'foo/bar.gif');
  123. $expected = "$scheme://styles/" . $this->style_name . "/$scheme/foo/bar.gif";
  124. $this->assertEqual($actual, $expected, 'Got the path for a relative file path.');
  125. }
  126. /**
  127. * Test image_style_url() with a file using the "public://" scheme.
  128. */
  129. function testImageStyleUrlAndPathPublic() {
  130. $this->_testImageStyleUrlAndPath('public');
  131. }
  132. /**
  133. * Test image_style_url() with a file using the "private://" scheme.
  134. */
  135. function testImageStyleUrlAndPathPrivate() {
  136. $this->_testImageStyleUrlAndPath('private');
  137. }
  138. /**
  139. * Test image_style_url() with the "public://" scheme and unclean URLs.
  140. */
  141. function testImageStylUrlAndPathPublicUnclean() {
  142. $this->_testImageStyleUrlAndPath('public', FALSE);
  143. }
  144. /**
  145. * Test image_style_url() with the "private://" schema and unclean URLs.
  146. */
  147. function testImageStyleUrlAndPathPrivateUnclean() {
  148. $this->_testImageStyleUrlAndPath('private', FALSE);
  149. }
  150. /**
  151. * Test image_style_url() with a file URL that has an extra slash in it.
  152. */
  153. function testImageStyleUrlExtraSlash() {
  154. $this->_testImageStyleUrlAndPath('public', TRUE, TRUE);
  155. }
  156. /**
  157. * Test image_style_url().
  158. */
  159. function _testImageStyleUrlAndPath($scheme, $clean_url = TRUE, $extra_slash = FALSE) {
  160. // Make the default scheme neither "public" nor "private" to verify the
  161. // functions work for other than the default scheme.
  162. variable_set('file_default_scheme', 'temporary');
  163. variable_set('clean_url', $clean_url);
  164. // Create the directories for the styles.
  165. $directory = $scheme . '://styles/' . $this->style_name;
  166. $status = file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
  167. $this->assertNotIdentical(FALSE, $status, 'Created the directory for the generated images for the test style.');
  168. // Create a working copy of the file.
  169. $files = $this->drupalGetTestFiles('image');
  170. $file = array_shift($files);
  171. $image_info = image_get_info($file->uri);
  172. $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
  173. // Let the image_module_test module know about this file, so it can claim
  174. // ownership in hook_file_download().
  175. variable_set('image_module_test_file_download', $original_uri);
  176. $this->assertNotIdentical(FALSE, $original_uri, 'Created the generated image file.');
  177. // Get the URL of a file that has not been generated and try to create it.
  178. $generated_uri = image_style_path($this->style_name, $original_uri);
  179. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  180. $generate_url = image_style_url($this->style_name, $original_uri);
  181. // Ensure that the tests still pass when the file is generated by accessing
  182. // a poorly constructed (but still valid) file URL that has an extra slash
  183. // in it.
  184. if ($extra_slash) {
  185. $modified_uri = str_replace('://', ':///', $original_uri);
  186. $this->assertNotEqual($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
  187. $generate_url = image_style_url($this->style_name, $modified_uri);
  188. }
  189. if (!$clean_url) {
  190. $this->assertTrue(strpos($generate_url, '?q=') !== FALSE, 'When using non-clean URLS, the system path contains the query string.');
  191. }
  192. // Add some extra chars to the token.
  193. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
  194. $this->assertResponse(403, 'Image was inaccessible at the URL wih an invalid token.');
  195. // Change the parameter name so the token is missing.
  196. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
  197. $this->assertResponse(403, 'Image was inaccessible at the URL wih a missing token.');
  198. // Fetch the URL that generates the file.
  199. $this->drupalGet($generate_url);
  200. $this->assertResponse(200, 'Image was generated at the URL.');
  201. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  202. $this->assertRaw(file_get_contents($generated_uri), 'URL returns expected file.');
  203. $generated_image_info = image_get_info($generated_uri);
  204. $this->assertEqual($this->drupalGetHeader('Content-Type'), $generated_image_info['mime_type'], 'Expected Content-Type was reported.');
  205. $this->assertEqual($this->drupalGetHeader('Content-Length'), $generated_image_info['file_size'], 'Expected Content-Length was reported.');
  206. if ($scheme == 'private') {
  207. $this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
  208. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate, post-check=0, pre-check=0', 'Cache-Control header was set to prevent caching.');
  209. $this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
  210. // Make sure that a second request to the already existing derivate works
  211. // too.
  212. $this->drupalGet($generate_url);
  213. $this->assertResponse(200, 'Image was generated at the URL.');
  214. // Make sure that access is denied for existing style files if we do not
  215. // have access.
  216. variable_del('image_module_test_file_download');
  217. $this->drupalGet($generate_url);
  218. $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
  219. // Repeat this with a different file that we do not have access to and
  220. // make sure that access is denied.
  221. $file_noaccess = array_shift($files);
  222. $original_uri_noaccess = file_unmanaged_copy($file_noaccess->uri, $scheme . '://', FILE_EXISTS_RENAME);
  223. $generated_uri_noaccess = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/'. drupal_basename($original_uri_noaccess);
  224. $this->assertFalse(file_exists($generated_uri_noaccess), 'Generated file does not exist.');
  225. $generate_url_noaccess = image_style_url($this->style_name, $original_uri_noaccess);
  226. $this->drupalGet($generate_url_noaccess);
  227. $this->assertResponse(403, 'Confirmed that access is denied for the private image style.');
  228. // Verify that images are not appended to the response. Currently this test only uses PNG images.
  229. if (strpos($generate_url, '.png') === FALSE ) {
  230. $this->fail('Confirming that private image styles are not appended require PNG file.');
  231. }
  232. else {
  233. // Check for PNG-Signature (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2) in the
  234. // response body.
  235. $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.');
  236. }
  237. }
  238. elseif ($clean_url) {
  239. // Add some extra chars to the token.
  240. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
  241. $this->assertResponse(200, 'Existing image was accessible at the URL wih an invalid token.');
  242. }
  243. // Allow insecure image derivatives to be created for the remainder of this
  244. // test.
  245. variable_set('image_allow_insecure_derivatives', TRUE);
  246. // Create another working copy of the file.
  247. $files = $this->drupalGetTestFiles('image');
  248. $file = array_shift($files);
  249. $image_info = image_get_info($file->uri);
  250. $original_uri = file_unmanaged_copy($file->uri, $scheme . '://', FILE_EXISTS_RENAME);
  251. // Let the image_module_test module know about this file, so it can claim
  252. // ownership in hook_file_download().
  253. variable_set('image_module_test_file_download', $original_uri);
  254. // Get the URL of a file that has not been generated and try to create it.
  255. $generated_uri = image_style_path($this->style_name, $original_uri);
  256. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  257. $generate_url = image_style_url($this->style_name, $original_uri);
  258. // Check that the image is accessible even without the security token.
  259. $this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $generate_url));
  260. $this->assertResponse(200, 'Image was accessible at the URL with a missing token.');
  261. // Check that a security token is still required when generating a second
  262. // image derivative using the first one as a source.
  263. $nested_uri = image_style_path($this->style_name, $generated_uri);
  264. $nested_url = image_style_url($this->style_name, $generated_uri);
  265. $nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrongparam=', $nested_url);
  266. $this->drupalGet($nested_url_with_wrong_token);
  267. $this->assertResponse(403, 'Image generated from an earlier derivative was inaccessible at the URL with a missing token.');
  268. // Check that this restriction cannot be bypassed by adding extra slashes
  269. // to the URL.
  270. $this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
  271. $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.');
  272. $this->drupalGet(substr_replace($nested_url_with_wrong_token, '/\styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
  273. $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.');
  274. // Make sure the image can still be generated if a correct token is used.
  275. $this->drupalGet($nested_url);
  276. $this->assertResponse(200, 'Image was accessible when a correct token was provided in the URL.');
  277. // Check that requesting a nonexistent image does not create any new
  278. // directories in the file system.
  279. $directory = $scheme . '://styles/' . $this->style_name . '/' . $scheme . '/' . $this->randomName();
  280. $this->drupalGet(file_create_url($directory . '/' . $this->randomName()));
  281. $this->assertFalse(file_exists($directory), 'New directory was not created in the filesystem when requesting an unauthorized image.');
  282. }
  283. }
  284. /**
  285. * Use the image_test.module's mock toolkit to ensure that the effects are
  286. * properly passing parameters to the image toolkit.
  287. */
  288. class ImageEffectsUnitTest extends ImageToolkitTestCase {
  289. public static function getInfo() {
  290. return array(
  291. 'name' => 'Image effects',
  292. 'description' => 'Test that the image effects pass parameters to the toolkit correctly.',
  293. 'group' => 'Image',
  294. );
  295. }
  296. function setUp() {
  297. parent::setUp('image_module_test');
  298. module_load_include('inc', 'image', 'image.effects');
  299. }
  300. /**
  301. * Test the image_resize_effect() function.
  302. */
  303. function testResizeEffect() {
  304. $this->assertTrue(image_resize_effect($this->image, array('width' => 1, 'height' => 2)), 'Function returned the expected value.');
  305. $this->assertToolkitOperationsCalled(array('resize'));
  306. // Check the parameters.
  307. $calls = image_test_get_all_calls();
  308. $this->assertEqual($calls['resize'][0][1], 1, 'Width was passed correctly');
  309. $this->assertEqual($calls['resize'][0][2], 2, 'Height was passed correctly');
  310. }
  311. /**
  312. * Test the image_scale_effect() function.
  313. */
  314. function testScaleEffect() {
  315. // @todo: need to test upscaling.
  316. $this->assertTrue(image_scale_effect($this->image, array('width' => 10, 'height' => 10)), 'Function returned the expected value.');
  317. $this->assertToolkitOperationsCalled(array('resize'));
  318. // Check the parameters.
  319. $calls = image_test_get_all_calls();
  320. $this->assertEqual($calls['resize'][0][1], 10, 'Width was passed correctly');
  321. $this->assertEqual($calls['resize'][0][2], 5, 'Height was based off aspect ratio and passed correctly');
  322. }
  323. /**
  324. * Test the image_crop_effect() function.
  325. */
  326. function testCropEffect() {
  327. // @todo should test the keyword offsets.
  328. $this->assertTrue(image_crop_effect($this->image, array('anchor' => 'top-1', 'width' => 3, 'height' => 4)), 'Function returned the expected value.');
  329. $this->assertToolkitOperationsCalled(array('crop'));
  330. // Check the parameters.
  331. $calls = image_test_get_all_calls();
  332. $this->assertEqual($calls['crop'][0][1], 0, 'X was passed correctly');
  333. $this->assertEqual($calls['crop'][0][2], 1, 'Y was passed correctly');
  334. $this->assertEqual($calls['crop'][0][3], 3, 'Width was passed correctly');
  335. $this->assertEqual($calls['crop'][0][4], 4, 'Height was passed correctly');
  336. }
  337. /**
  338. * Test the image_scale_and_crop_effect() function.
  339. */
  340. function testScaleAndCropEffect() {
  341. $this->assertTrue(image_scale_and_crop_effect($this->image, array('width' => 5, 'height' => 10)), 'Function returned the expected value.');
  342. $this->assertToolkitOperationsCalled(array('resize', 'crop'));
  343. // Check the parameters.
  344. $calls = image_test_get_all_calls();
  345. $this->assertEqual($calls['crop'][0][1], 7.5, 'X was computed and passed correctly');
  346. $this->assertEqual($calls['crop'][0][2], 0, 'Y was computed and passed correctly');
  347. $this->assertEqual($calls['crop'][0][3], 5, 'Width was computed and passed correctly');
  348. $this->assertEqual($calls['crop'][0][4], 10, 'Height was computed and passed correctly');
  349. }
  350. /**
  351. * Test the image_desaturate_effect() function.
  352. */
  353. function testDesaturateEffect() {
  354. $this->assertTrue(image_desaturate_effect($this->image, array()), 'Function returned the expected value.');
  355. $this->assertToolkitOperationsCalled(array('desaturate'));
  356. // Check the parameters.
  357. $calls = image_test_get_all_calls();
  358. $this->assertEqual(count($calls['desaturate'][0]), 1, 'Only the image was passed.');
  359. }
  360. /**
  361. * Test the image_rotate_effect() function.
  362. */
  363. function testRotateEffect() {
  364. // @todo: need to test with 'random' => TRUE
  365. $this->assertTrue(image_rotate_effect($this->image, array('degrees' => 90, 'bgcolor' => '#fff')), 'Function returned the expected value.');
  366. $this->assertToolkitOperationsCalled(array('rotate'));
  367. // Check the parameters.
  368. $calls = image_test_get_all_calls();
  369. $this->assertEqual($calls['rotate'][0][1], 90, 'Degrees were passed correctly');
  370. $this->assertEqual($calls['rotate'][0][2], 0xffffff, 'Background color was passed correctly');
  371. }
  372. /**
  373. * Test image effect caching.
  374. */
  375. function testImageEffectsCaching() {
  376. $image_effect_definitions_called = &drupal_static('image_module_test_image_effect_info_alter');
  377. // First call should grab a fresh copy of the data.
  378. $effects = image_effect_definitions();
  379. $this->assertTrue($image_effect_definitions_called === 1, 'image_effect_definitions() generated data.');
  380. // Second call should come from cache.
  381. drupal_static_reset('image_effect_definitions');
  382. drupal_static_reset('image_module_test_image_effect_info_alter');
  383. $cached_effects = image_effect_definitions();
  384. $this->assertTrue(is_null($image_effect_definitions_called), 'image_effect_definitions() returned data from cache.');
  385. $this->assertTrue($effects == $cached_effects, 'Cached effects are the same as generated effects.');
  386. }
  387. }
  388. /**
  389. * Tests creation, deletion, and editing of image styles and effects.
  390. */
  391. class ImageAdminStylesUnitTest extends ImageFieldTestCase {
  392. public static function getInfo() {
  393. return array(
  394. 'name' => 'Image styles and effects UI configuration',
  395. 'description' => 'Tests creation, deletion, and editing of image styles and effects at the UI level.',
  396. 'group' => 'Image',
  397. );
  398. }
  399. /**
  400. * Given an image style, generate an image.
  401. */
  402. function createSampleImage($style) {
  403. static $file_path;
  404. // First, we need to make sure we have an image in our testing
  405. // file directory. Copy over an image on the first run.
  406. if (!isset($file_path)) {
  407. $files = $this->drupalGetTestFiles('image');
  408. $file = reset($files);
  409. $file_path = file_unmanaged_copy($file->uri);
  410. }
  411. return image_style_url($style['name'], $file_path) ? $file_path : FALSE;
  412. }
  413. /**
  414. * Count the number of images currently create for a style.
  415. */
  416. function getImageCount($style) {
  417. return count(file_scan_directory('public://styles/' . $style['name'], '/.*/'));
  418. }
  419. /**
  420. * Test creating an image style with a numeric name and ensuring it can be
  421. * applied to an image.
  422. */
  423. function testNumericStyleName() {
  424. $style_name = rand();
  425. $style_label = $this->randomString();
  426. $edit = array(
  427. 'name' => $style_name,
  428. 'label' => $style_label,
  429. );
  430. $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
  431. $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
  432. $options = image_style_options();
  433. $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', array('%key' => $style_name)));
  434. }
  435. /**
  436. * General test to add a style, add/remove/edit effects to it, then delete it.
  437. */
  438. function testStyle() {
  439. // Setup a style to be created and effects to add to it.
  440. $style_name = strtolower($this->randomName(10));
  441. $style_label = $this->randomString();
  442. $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
  443. $effect_edits = array(
  444. 'image_resize' => array(
  445. 'data[width]' => 100,
  446. 'data[height]' => 101,
  447. ),
  448. 'image_scale' => array(
  449. 'data[width]' => 110,
  450. 'data[height]' => 111,
  451. 'data[upscale]' => 1,
  452. ),
  453. 'image_scale_and_crop' => array(
  454. 'data[width]' => 120,
  455. 'data[height]' => 121,
  456. ),
  457. 'image_crop' => array(
  458. 'data[width]' => 130,
  459. 'data[height]' => 131,
  460. 'data[anchor]' => 'center-center',
  461. ),
  462. 'image_desaturate' => array(
  463. // No options for desaturate.
  464. ),
  465. 'image_rotate' => array(
  466. 'data[degrees]' => 5,
  467. 'data[random]' => 1,
  468. 'data[bgcolor]' => '#FFFF00',
  469. ),
  470. );
  471. // Add style form.
  472. $edit = array(
  473. 'name' => $style_name,
  474. 'label' => $style_label,
  475. );
  476. $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
  477. $this->assertRaw(t('Style %name was created.', array('%name' => $style_label)), 'Image style successfully created.');
  478. // Add effect form.
  479. // Add each sample effect to the style.
  480. foreach ($effect_edits as $effect => $edit) {
  481. // Add the effect.
  482. $this->drupalPost($style_path, array('new' => $effect), t('Add'));
  483. if (!empty($edit)) {
  484. $this->drupalPost(NULL, $edit, t('Add effect'));
  485. }
  486. }
  487. // Edit effect form.
  488. // Revisit each form to make sure the effect was saved.
  489. drupal_static_reset('image_styles');
  490. $style = image_style_load($style_name);
  491. foreach ($style['effects'] as $ieid => $effect) {
  492. $this->drupalGet($style_path . '/effects/' . $ieid);
  493. foreach ($effect_edits[$effect['name']] as $field => $value) {
  494. $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)));
  495. }
  496. }
  497. // Image style overview form (ordering and renaming).
  498. // Confirm the order of effects is maintained according to the order we
  499. // added the fields.
  500. $effect_edits_order = array_keys($effect_edits);
  501. $effects_order = array_values($style['effects']);
  502. $order_correct = TRUE;
  503. foreach ($effects_order as $index => $effect) {
  504. if ($effect_edits_order[$index] != $effect['name']) {
  505. $order_correct = FALSE;
  506. }
  507. }
  508. $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
  509. // Test the style overview form.
  510. // Change the name of the style and adjust the weights of effects.
  511. $style_name = strtolower($this->randomName(10));
  512. $style_label = $this->randomString();
  513. $weight = count($effect_edits);
  514. $edit = array(
  515. 'name' => $style_name,
  516. 'label' => $style_label,
  517. );
  518. foreach ($style['effects'] as $ieid => $effect) {
  519. $edit['effects[' . $ieid . '][weight]'] = $weight;
  520. $weight--;
  521. }
  522. // Create an image to make sure it gets flushed after saving.
  523. $image_path = $this->createSampleImage($style);
  524. $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
  525. $this->drupalPost($style_path, $edit, t('Update style'));
  526. // Note that after changing the style name, the style path is changed.
  527. $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
  528. // Check that the URL was updated.
  529. $this->drupalGet($style_path);
  530. $this->assertResponse(200, format_string('Image style %original renamed to %new', array('%original' => $style['label'], '%new' => $style_label)));
  531. // Check that the image was flushed after updating the style.
  532. // This is especially important when renaming the style. Make sure that
  533. // the old image directory has been deleted.
  534. $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'])));
  535. // Load the style by the new name with the new weights.
  536. drupal_static_reset('image_styles');
  537. $style = image_style_load($style_name, NULL);
  538. // Confirm the new style order was saved.
  539. $effect_edits_order = array_reverse($effect_edits_order);
  540. $effects_order = array_values($style['effects']);
  541. $order_correct = TRUE;
  542. foreach ($effects_order as $index => $effect) {
  543. if ($effect_edits_order[$index] != $effect['name']) {
  544. $order_correct = FALSE;
  545. }
  546. }
  547. $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
  548. // Image effect deletion form.
  549. // Create an image to make sure it gets flushed after deleting an effect.
  550. $image_path = $this->createSampleImage($style);
  551. $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
  552. // Test effect deletion form.
  553. $effect = array_pop($style['effects']);
  554. $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
  555. $this->assertRaw(t('The image effect %name has been deleted.', array('%name' => $effect['label'])), 'Image effect deleted.');
  556. // Style deletion form.
  557. // Delete the style.
  558. $this->drupalPost('admin/config/media/image-styles/delete/' . $style_name, array(), t('Delete'));
  559. // Confirm the style directory has been removed.
  560. $directory = file_default_scheme() . '://styles/' . $style_name;
  561. $this->assertFalse(is_dir($directory), format_string('Image style %style directory removed on style deletion.', array('%style' => $style['label'])));
  562. drupal_static_reset('image_styles');
  563. $this->assertFalse(image_style_load($style_name), format_string('Image style %style successfully deleted.', array('%style' => $style['label'])));
  564. }
  565. /**
  566. * Test to override, edit, then revert a style.
  567. */
  568. function testDefaultStyle() {
  569. // Setup a style to be created and effects to add to it.
  570. $style_name = 'thumbnail';
  571. $style_label = 'Thumbnail (100x100)';
  572. $edit_path = 'admin/config/media/image-styles/edit/' . $style_name;
  573. $delete_path = 'admin/config/media/image-styles/delete/' . $style_name;
  574. $revert_path = 'admin/config/media/image-styles/revert/' . $style_name;
  575. // Ensure deleting a default is not possible.
  576. $this->drupalGet($delete_path);
  577. $this->assertText(t('Page not found'), 'Default styles may not be deleted.');
  578. // Ensure that editing a default is not possible (without overriding).
  579. $this->drupalGet($edit_path);
  580. $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
  581. $this->assertTrue($disabled_field, 'Default styles may not be renamed.');
  582. $this->assertNoField('edit-submit', 'Default styles may not be edited.');
  583. $this->assertNoField('edit-add', 'Default styles may not have new effects added.');
  584. // Create an image to make sure the default works before overriding.
  585. drupal_static_reset('image_styles');
  586. $style = image_style_load($style_name);
  587. $image_path = $this->createSampleImage($style);
  588. $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
  589. // Verify that effects attached to a default style do not have an ieid key.
  590. foreach ($style['effects'] as $effect) {
  591. $this->assertFalse(isset($effect['ieid']), format_string('The %effect effect does not have an ieid.', array('%effect' => $effect['name'])));
  592. }
  593. // Override the default.
  594. $this->drupalPost($edit_path, array(), t('Override defaults'));
  595. $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.');
  596. // Add sample effect to the overridden style.
  597. $this->drupalPost($edit_path, array('new' => 'image_desaturate'), t('Add'));
  598. drupal_static_reset('image_styles');
  599. $style = image_style_load($style_name);
  600. // Verify that effects attached to the style have an ieid now.
  601. foreach ($style['effects'] as $effect) {
  602. $this->assertTrue(isset($effect['ieid']), format_string('The %effect effect has an ieid.', array('%effect' => $effect['name'])));
  603. }
  604. // The style should now have 2 effect, the original scale provided by core
  605. // and the desaturate effect we added in the override.
  606. $effects = array_values($style['effects']);
  607. $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the overridden style.');
  608. $this->assertEqual($effects[1]['name'], 'image_desaturate', 'The added effect exists in the overridden style.');
  609. // Check that we are able to rename an overridden style.
  610. $this->drupalGet($edit_path);
  611. $disabled_field = $this->xpath('//input[@id=:id and @disabled="disabled"]', array(':id' => 'edit-name'));
  612. $this->assertFalse($disabled_field, 'Overridden styles may be renamed.');
  613. // Create an image to ensure the override works properly.
  614. $image_path = $this->createSampleImage($style);
  615. $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['label'], '%file' => $image_path)));
  616. // Revert the image style.
  617. $this->drupalPost($revert_path, array(), t('Revert'));
  618. drupal_static_reset('image_styles');
  619. $style = image_style_load($style_name);
  620. // The style should now have the single effect for scale.
  621. $effects = array_values($style['effects']);
  622. $this->assertEqual($effects[0]['name'], 'image_scale', 'The default effect still exists in the reverted style.');
  623. $this->assertFalse(array_key_exists(1, $effects), 'The added effect has been removed in the reverted style.');
  624. }
  625. /**
  626. * Test deleting a style and choosing a replacement style.
  627. */
  628. function testStyleReplacement() {
  629. // Create a new style.
  630. $style_name = strtolower($this->randomName(10));
  631. $style_label = $this->randomString();
  632. image_style_save(array('name' => $style_name, 'label' => $style_label));
  633. $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
  634. // Create an image field that uses the new style.
  635. $field_name = strtolower($this->randomName(10));
  636. $this->createImageField($field_name, 'article');
  637. $instance = field_info_instance('node', $field_name, 'article');
  638. $instance['display']['default']['type'] = 'image';
  639. $instance['display']['default']['settings']['image_style'] = $style_name;
  640. field_update_instance($instance);
  641. // Create a new node with an image attached.
  642. $test_image = current($this->drupalGetTestFiles('image'));
  643. $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
  644. $node = node_load($nid);
  645. // Test that image is displayed using newly created style.
  646. $this->drupalGet('node/' . $nid);
  647. $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)));
  648. // Rename the style and make sure the image field is updated.
  649. $new_style_name = strtolower($this->randomName(10));
  650. $new_style_label = $this->randomString();
  651. $edit = array(
  652. 'name' => $new_style_name,
  653. 'label' => $new_style_label,
  654. );
  655. $this->drupalPost('admin/config/media/image-styles/edit/' . $style_name, $edit, t('Update style'));
  656. $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)));
  657. $this->drupalGet('node/' . $nid);
  658. $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.'));
  659. // Delete the style and choose a replacement style.
  660. $edit = array(
  661. 'replacement' => 'thumbnail',
  662. );
  663. $this->drupalPost('admin/config/media/image-styles/delete/' . $new_style_name, $edit, t('Delete'));
  664. $message = t('Style %name was deleted.', array('%name' => $new_style_label));
  665. $this->assertRaw($message, $message);
  666. $this->drupalGet('node/' . $nid);
  667. $this->assertRaw(check_plain(image_style_url('thumbnail', $node->{$field_name}[LANGUAGE_NONE][0]['uri'])), format_string('Image displayed using style replacement style.'));
  668. }
  669. }
  670. /**
  671. * Test class to check that formatters and display settings are working.
  672. */
  673. class ImageFieldDisplayTestCase extends ImageFieldTestCase {
  674. public static function getInfo() {
  675. return array(
  676. 'name' => 'Image field display tests',
  677. 'description' => 'Test the display of image fields.',
  678. 'group' => 'Image',
  679. );
  680. }
  681. /**
  682. * Test image formatters on node display for public files.
  683. */
  684. function testImageFieldFormattersPublic() {
  685. $this->_testImageFieldFormatters('public');
  686. }
  687. /**
  688. * Test image formatters on node display for private files.
  689. */
  690. function testImageFieldFormattersPrivate() {
  691. // Remove access content permission from anonymous users.
  692. user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array('access content' => FALSE));
  693. $this->_testImageFieldFormatters('private');
  694. }
  695. /**
  696. * Test image formatters on node display.
  697. */
  698. function _testImageFieldFormatters($scheme) {
  699. $field_name = strtolower($this->randomName());
  700. $this->createImageField($field_name, 'article', array('uri_scheme' => $scheme));
  701. // Create a new node with an image attached.
  702. $test_image = current($this->drupalGetTestFiles('image'));
  703. $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
  704. $node = node_load($nid, NULL, TRUE);
  705. // Test that the default formatter is being used.
  706. $image_uri = $node->{$field_name}[LANGUAGE_NONE][0]['uri'];
  707. $image_info = array(
  708. 'path' => $image_uri,
  709. 'width' => 40,
  710. 'height' => 20,
  711. );
  712. $default_output = theme('image', $image_info);
  713. $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
  714. // Test the image linked to file formatter.
  715. $instance = field_info_instance('node', $field_name, 'article');
  716. $instance['display']['default']['type'] = 'image';
  717. $instance['display']['default']['settings']['image_link'] = 'file';
  718. field_update_instance($instance);
  719. $default_output = l(theme('image', $image_info), file_create_url($image_uri), array('html' => TRUE));
  720. $this->drupalGet('node/' . $nid);
  721. $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
  722. // Verify that the image can be downloaded.
  723. $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
  724. if ($scheme == 'private') {
  725. // Only verify HTTP headers when using private scheme and the headers are
  726. // sent by Drupal.
  727. $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
  728. $this->assertEqual($this->drupalGetHeader('Cache-Control'), 'private', 'Cache-Control header was sent.');
  729. // Log out and try to access the file.
  730. $this->drupalLogout();
  731. $this->drupalGet(file_create_url($image_uri));
  732. $this->assertResponse('403', 'Access denied to original image as anonymous user.');
  733. // Log in again.
  734. $this->drupalLogin($this->admin_user);
  735. }
  736. // Test the image linked to content formatter.
  737. $instance['display']['default']['settings']['image_link'] = 'content';
  738. field_update_instance($instance);
  739. $default_output = l(theme('image', $image_info), 'node/' . $nid, array('html' => TRUE, 'attributes' => array('class' => 'active')));
  740. $this->drupalGet('node/' . $nid);
  741. $this->assertRaw($default_output, 'Image linked to content formatter displaying correctly on full node view.');
  742. // Test the image style 'thumbnail' formatter.
  743. $instance['display']['default']['settings']['image_link'] = '';
  744. $instance['display']['default']['settings']['image_style'] = 'thumbnail';
  745. field_update_instance($instance);
  746. // Ensure the derivative image is generated so we do not have to deal with
  747. // image style callback paths.
  748. $this->drupalGet(image_style_url('thumbnail', $image_uri));
  749. // Need to create the URL again since it will change if clean URLs
  750. // are disabled.
  751. $image_info['path'] = image_style_url('thumbnail', $image_uri);
  752. $image_info['width'] = 100;
  753. $image_info['height'] = 50;
  754. $default_output = theme('image', $image_info);
  755. $this->drupalGet('node/' . $nid);
  756. $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
  757. if ($scheme == 'private') {
  758. // Log out and try to access the file.
  759. $this->drupalLogout();
  760. $this->drupalGet(image_style_url('thumbnail', $image_uri));
  761. $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
  762. }
  763. }
  764. /**
  765. * Tests for image field settings.
  766. */
  767. function testImageFieldSettings() {
  768. $test_image = current($this->drupalGetTestFiles('image'));
  769. list(, $test_image_extension) = explode('.', $test_image->filename);
  770. $field_name = strtolower($this->randomName());
  771. $instance_settings = array(
  772. 'alt_field' => 1,
  773. 'file_extensions' => $test_image_extension,
  774. 'max_filesize' => '50 KB',
  775. 'max_resolution' => '100x100',
  776. 'min_resolution' => '10x10',
  777. 'title_field' => 1,
  778. );
  779. $widget_settings = array(
  780. 'preview_image_style' => 'medium',
  781. );
  782. $field = $this->createImageField($field_name, 'article', array(), $instance_settings, $widget_settings);
  783. $field['deleted'] = 0;
  784. $table = _field_sql_storage_tablename($field);
  785. $schema = drupal_get_schema($table, TRUE);
  786. $instance = field_info_instance('node', $field_name, 'article');
  787. $this->drupalGet('node/add/article');
  788. $this->assertText(t('Files must be less than 50 KB.'), 'Image widget max file size is displayed on article form.');
  789. $this->assertText(t('Allowed file types: ' . $test_image_extension . '.'), 'Image widget allowed file types displayed on article form.');
  790. $this->assertText(t('Images must be between 10x10 and 100x100 pixels.'), 'Image widget allowed resolution displayed on article form.');
  791. // We have to create the article first and then edit it because the alt
  792. // and title fields do not display until the image has been attached.
  793. $nid = $this->uploadNodeImage($test_image, $field_name, 'article');
  794. $this->drupalGet('node/' . $nid . '/edit');
  795. $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][alt]', '', 'Alt field displayed on article form.');
  796. $this->assertFieldByName($field_name . '[' . LANGUAGE_NONE . '][0][title]', '', 'Title field displayed on article form.');
  797. // Verify that the attached image is being previewed using the 'medium'
  798. // style.
  799. $node = node_load($nid, NULL, TRUE);
  800. $image_info = array(
  801. 'path' => image_style_url('medium', $node->{$field_name}[LANGUAGE_NONE][0]['uri']),
  802. 'width' => 220,
  803. 'height' => 110,
  804. );
  805. $default_output = theme('image', $image_info);
  806. $this->assertRaw($default_output, "Preview image is displayed using 'medium' style.");
  807. // Add alt/title fields to the image and verify that they are displayed.
  808. $image_info = array(
  809. 'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
  810. 'alt' => $this->randomName(),
  811. 'title' => $this->randomName(),
  812. 'width' => 40,
  813. 'height' => 20,
  814. );
  815. $edit = array(
  816. $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $image_info['alt'],
  817. $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $image_info['title'],
  818. );
  819. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  820. $default_output = theme('image', $image_info);
  821. $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
  822. // Verify that alt/title longer than allowed results in a validation error.
  823. $test_size = 2000;
  824. $edit = array(
  825. $field_name . '[' . LANGUAGE_NONE . '][0][alt]' => $this->randomName($test_size),
  826. $field_name . '[' . LANGUAGE_NONE . '][0][title]' => $this->randomName($test_size),
  827. );
  828. $this->drupalPost('node/' . $nid . '/edit', $edit, t('Save'));
  829. $this->assertRaw(t('Alternate text cannot be longer than %max characters but is currently %length characters long.', array(
  830. '%max' => $schema['fields'][$field_name .'_alt']['length'],
  831. '%length' => $test_size,
  832. )));
  833. $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', array(
  834. '%max' => $schema['fields'][$field_name .'_title']['length'],
  835. '%length' => $test_size,
  836. )));
  837. }
  838. /**
  839. * Test passing attributes into the image field formatters.
  840. */
  841. function testImageFieldFormatterAttributes() {
  842. $image = theme('image_formatter', array(
  843. 'item' => array(
  844. 'uri' => 'http://example.com/example.png',
  845. 'attributes' => array(
  846. 'data-image-field-formatter' => 'testFound',
  847. ),
  848. 'alt' => t('Image field formatter attribute test.'),
  849. 'title' => t('Image field formatter'),
  850. ),
  851. ));
  852. $this->assertTrue(stripos($image, 'testFound') > 0, 'Image field formatters can have attributes.');
  853. }
  854. /**
  855. * Test use of a default image with an image field.
  856. */
  857. function testImageFieldDefaultImage() {
  858. // Create a new image field.
  859. $field_name = strtolower($this->randomName());
  860. $this->createImageField($field_name, 'article');
  861. // Create a new node, with no images and verify that no images are
  862. // displayed.
  863. $node = $this->drupalCreateNode(array('type' => 'article'));
  864. $this->drupalGet('node/' . $node->nid);
  865. // Verify that no image is displayed on the page by checking for the class
  866. // that would be used on the image field.
  867. $this->assertNoPattern('<div class="(.*?)field-name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
  868. // Add a default image to the public imagefield instance.
  869. $images = $this->drupalGetTestFiles('image');
  870. $edit = array(
  871. 'files[field_settings_default_image]' => drupal_realpath($images[0]->uri),
  872. );
  873. $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
  874. // Clear field info cache so the new default image is detected.
  875. field_info_cache_clear();
  876. $field = field_info_field($field_name);
  877. $image = file_load($field['settings']['default_image']);
  878. $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
  879. $default_output = theme('image', array('path' => $image->uri));
  880. $this->drupalGet('node/' . $node->nid);
  881. $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
  882. // Create a node with an image attached and ensure that the default image
  883. // is not displayed.
  884. $nid = $this->uploadNodeImage($images[1], $field_name, 'article');
  885. $node = node_load($nid, NULL, TRUE);
  886. $image_info = array(
  887. 'path' => $node->{$field_name}[LANGUAGE_NONE][0]['uri'],
  888. 'width' => 40,
  889. 'height' => 20,
  890. );
  891. $image_output = theme('image', $image_info);
  892. $this->drupalGet('node/' . $nid);
  893. $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
  894. $this->assertRaw($image_output, 'User supplied image is displayed.');
  895. // Remove default image from the field and make sure it is no longer used.
  896. $edit = array(
  897. 'field[settings][default_image][fid]' => 0,
  898. );
  899. $this->drupalPost('admin/structure/types/manage/article/fields/' . $field_name, $edit, t('Save settings'));
  900. // Clear field info cache so the new default image is detected.
  901. field_info_cache_clear();
  902. $field = field_info_field($field_name);
  903. $this->assertFalse($field['settings']['default_image'], 'Default image removed from field.');
  904. // Create an image field that uses the private:// scheme and test that the
  905. // default image works as expected.
  906. $private_field_name = strtolower($this->randomName());
  907. $this->createImageField($private_field_name, 'article', array('uri_scheme' => 'private'));
  908. // Add a default image to the new field.
  909. $edit = array(
  910. 'files[field_settings_default_image]' => drupal_realpath($images[1]->uri),
  911. );
  912. $this->drupalPost('admin/structure/types/manage/article/fields/' . $private_field_name, $edit, t('Save settings'));
  913. $private_field = field_info_field($private_field_name);
  914. $image = file_load($private_field['settings']['default_image']);
  915. $this->assertEqual('private', file_uri_scheme($image->uri), 'Default image uses private:// scheme.');
  916. $this->assertTrue($image->status == FILE_STATUS_PERMANENT, 'The default image status is permanent.');
  917. // Create a new node with no image attached and ensure that default private
  918. // image is displayed.
  919. $node = $this->drupalCreateNode(array('type' => 'article'));
  920. $default_output = theme('image', array('path' => $image->uri));
  921. $this->drupalGet('node/' . $node->nid);
  922. $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');
  923. }
  924. }
  925. /**
  926. * Test class to check for various validations.
  927. */
  928. class ImageFieldValidateTestCase extends ImageFieldTestCase {
  929. public static function getInfo() {
  930. return array(
  931. 'name' => 'Image field validation tests',
  932. 'description' => 'Tests validation functions such as min/max resolution.',
  933. 'group' => 'Image',
  934. );
  935. }
  936. /**
  937. * Test min/max resolution settings.
  938. */
  939. function testResolution() {
  940. $field_name = strtolower($this->randomName());
  941. $min_resolution = 50;
  942. $max_resolution = 100;
  943. $instance_settings = array(
  944. 'max_resolution' => $max_resolution . 'x' . $max_resolution,
  945. 'min_resolution' => $min_resolution . 'x' . $min_resolution,
  946. );
  947. $this->createImageField($field_name, 'article', array(), $instance_settings);
  948. // We want a test image that is too small, and a test image that is too
  949. // big, so cycle through test image files until we have what we need.
  950. $image_that_is_too_big = FALSE;
  951. $image_that_is_too_small = FALSE;
  952. foreach ($this->drupalGetTestFiles('image') as $image) {
  953. $info = image_get_info($image->uri);
  954. if ($info['width'] > $max_resolution) {
  955. $image_that_is_too_big = $image;
  956. }
  957. if ($info['width'] < $min_resolution) {
  958. $image_that_is_too_small = $image;
  959. }
  960. if ($image_that_is_too_small && $image_that_is_too_big) {
  961. break;
  962. }
  963. }
  964. $nid = $this->uploadNodeImage($image_that_is_too_small, $field_name, 'article');
  965. $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.');
  966. $nid = $this->uploadNodeImage($image_that_is_too_big, $field_name, 'article');
  967. $this->assertText(t('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.'), 'Image exceeding max resolution was properly resized.');
  968. }
  969. }
  970. /**
  971. * Tests that images have correct dimensions when styled.
  972. */
  973. class ImageDimensionsTestCase extends DrupalWebTestCase {
  974. public static function getInfo() {
  975. return array(
  976. 'name' => 'Image dimensions',
  977. 'description' => 'Tests that images have correct dimensions when styled.',
  978. 'group' => 'Image',
  979. );
  980. }
  981. function setUp() {
  982. parent::setUp('image_module_test');
  983. }
  984. /**
  985. * Test styled image dimensions cumulatively.
  986. */
  987. function testImageDimensions() {
  988. // Create a working copy of the file.
  989. $files = $this->drupalGetTestFiles('image');
  990. $file = reset($files);
  991. $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
  992. // Create a style.
  993. $style = image_style_save(array('name' => 'test', 'label' => 'Test'));
  994. $generated_uri = 'public://styles/test/public/'. drupal_basename($original_uri);
  995. $url = image_style_url('test', $original_uri);
  996. $variables = array(
  997. 'style_name' => 'test',
  998. 'path' => $original_uri,
  999. 'width' => 40,
  1000. 'height' => 20,
  1001. );
  1002. // Scale an image that is wider than it is high.
  1003. $effect = array(
  1004. 'name' => 'image_scale',
  1005. 'data' => array(
  1006. 'width' => 120,
  1007. 'height' => 90,
  1008. 'upscale' => TRUE,
  1009. ),
  1010. 'isid' => $style['isid'],
  1011. );
  1012. image_effect_save($effect);
  1013. $img_tag = theme_image_style($variables);
  1014. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="120" height="60" alt="" />', 'Expected img tag was found.');
  1015. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1016. $this->drupalGet($url);
  1017. $this->assertResponse(200, 'Image was generated at the URL.');
  1018. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1019. $image_info = image_get_info($generated_uri);
  1020. $this->assertEqual($image_info['width'], 120, 'Expected width was found.');
  1021. $this->assertEqual($image_info['height'], 60, 'Expected height was found.');
  1022. // Rotate 90 degrees anticlockwise.
  1023. $effect = array(
  1024. 'name' => 'image_rotate',
  1025. 'data' => array(
  1026. 'degrees' => -90,
  1027. 'random' => FALSE,
  1028. ),
  1029. 'isid' => $style['isid'],
  1030. );
  1031. image_effect_save($effect);
  1032. $img_tag = theme_image_style($variables);
  1033. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="60" height="120" alt="" />', 'Expected img tag was found.');
  1034. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1035. $this->drupalGet($url);
  1036. $this->assertResponse(200, 'Image was generated at the URL.');
  1037. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1038. $image_info = image_get_info($generated_uri);
  1039. $this->assertEqual($image_info['width'], 60, 'Expected width was found.');
  1040. $this->assertEqual($image_info['height'], 120, 'Expected height was found.');
  1041. // Scale an image that is higher than it is wide (rotated by previous effect).
  1042. $effect = array(
  1043. 'name' => 'image_scale',
  1044. 'data' => array(
  1045. 'width' => 120,
  1046. 'height' => 90,
  1047. 'upscale' => TRUE,
  1048. ),
  1049. 'isid' => $style['isid'],
  1050. );
  1051. image_effect_save($effect);
  1052. $img_tag = theme_image_style($variables);
  1053. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
  1054. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1055. $this->drupalGet($url);
  1056. $this->assertResponse(200, 'Image was generated at the URL.');
  1057. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1058. $image_info = image_get_info($generated_uri);
  1059. $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
  1060. $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
  1061. // Test upscale disabled.
  1062. $effect = array(
  1063. 'name' => 'image_scale',
  1064. 'data' => array(
  1065. 'width' => 400,
  1066. 'height' => 200,
  1067. 'upscale' => FALSE,
  1068. ),
  1069. 'isid' => $style['isid'],
  1070. );
  1071. image_effect_save($effect);
  1072. $img_tag = theme_image_style($variables);
  1073. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
  1074. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1075. $this->drupalGet($url);
  1076. $this->assertResponse(200, 'Image was generated at the URL.');
  1077. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1078. $image_info = image_get_info($generated_uri);
  1079. $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
  1080. $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
  1081. // Add a desaturate effect.
  1082. $effect = array(
  1083. 'name' => 'image_desaturate',
  1084. 'data' => array(),
  1085. 'isid' => $style['isid'],
  1086. );
  1087. image_effect_save($effect);
  1088. $img_tag = theme_image_style($variables);
  1089. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="45" height="90" alt="" />', 'Expected img tag was found.');
  1090. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1091. $this->drupalGet($url);
  1092. $this->assertResponse(200, 'Image was generated at the URL.');
  1093. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1094. $image_info = image_get_info($generated_uri);
  1095. $this->assertEqual($image_info['width'], 45, 'Expected width was found.');
  1096. $this->assertEqual($image_info['height'], 90, 'Expected height was found.');
  1097. // Add a random rotate effect.
  1098. $effect = array(
  1099. 'name' => 'image_rotate',
  1100. 'data' => array(
  1101. 'degrees' => 180,
  1102. 'random' => TRUE,
  1103. ),
  1104. 'isid' => $style['isid'],
  1105. );
  1106. image_effect_save($effect);
  1107. $img_tag = theme_image_style($variables);
  1108. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
  1109. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1110. $this->drupalGet($url);
  1111. $this->assertResponse(200, 'Image was generated at the URL.');
  1112. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1113. // Add a crop effect.
  1114. $effect = array(
  1115. 'name' => 'image_crop',
  1116. 'data' => array(
  1117. 'width' => 30,
  1118. 'height' => 30,
  1119. 'anchor' => 'center-center',
  1120. ),
  1121. 'isid' => $style['isid'],
  1122. );
  1123. image_effect_save($effect);
  1124. $img_tag = theme_image_style($variables);
  1125. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" width="30" height="30" alt="" />', 'Expected img tag was found.');
  1126. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1127. $this->drupalGet($url);
  1128. $this->assertResponse(200, 'Image was generated at the URL.');
  1129. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1130. $image_info = image_get_info($generated_uri);
  1131. $this->assertEqual($image_info['width'], 30, 'Expected width was found.');
  1132. $this->assertEqual($image_info['height'], 30, 'Expected height was found.');
  1133. // Rotate to a non-multiple of 90 degrees.
  1134. $effect = array(
  1135. 'name' => 'image_rotate',
  1136. 'data' => array(
  1137. 'degrees' => 57,
  1138. 'random' => FALSE,
  1139. ),
  1140. 'isid' => $style['isid'],
  1141. );
  1142. $effect = image_effect_save($effect);
  1143. $img_tag = theme_image_style($variables);
  1144. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
  1145. $this->assertFalse(file_exists($generated_uri), 'Generated file does not exist.');
  1146. $this->drupalGet($url);
  1147. $this->assertResponse(200, 'Image was generated at the URL.');
  1148. $this->assertTrue(file_exists($generated_uri), 'Generated file does exist after we accessed it.');
  1149. image_effect_delete($effect);
  1150. // Ensure that an effect with no dimensions callback unsets the dimensions.
  1151. // This ensures compatibility with 7.0 contrib modules.
  1152. $effect = array(
  1153. 'name' => 'image_module_test_null',
  1154. 'data' => array(),
  1155. 'isid' => $style['isid'],
  1156. );
  1157. image_effect_save($effect);
  1158. $img_tag = theme_image_style($variables);
  1159. $this->assertEqual($img_tag, '<img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" />', 'Expected img tag was found.');
  1160. }
  1161. }
  1162. /**
  1163. * Tests image_dimensions_scale().
  1164. */
  1165. class ImageDimensionsScaleTestCase extends DrupalUnitTestCase {
  1166. public static function getInfo() {
  1167. return array(
  1168. 'name' => 'image_dimensions_scale()',
  1169. 'description' => 'Tests all control flow branches in image_dimensions_scale().',
  1170. 'group' => 'Image',
  1171. );
  1172. }
  1173. /**
  1174. * Tests all control flow branches in image_dimensions_scale().
  1175. */
  1176. function testImageDimensionsScale() {
  1177. // Define input / output datasets to test different branch conditions.
  1178. $test = array();
  1179. // Test branch conditions:
  1180. // - No height.
  1181. // - Upscale, don't need to upscale.
  1182. $tests[] = array(
  1183. 'input' => array(
  1184. 'dimensions' => array(
  1185. 'width' => 1000,
  1186. 'height' => 2000,
  1187. ),
  1188. 'width' => 200,
  1189. 'height' => NULL,
  1190. 'upscale' => TRUE,
  1191. ),
  1192. 'output' => array(
  1193. 'dimensions' => array(
  1194. 'width' => 200,
  1195. 'height' => 400,
  1196. ),
  1197. 'return_value' => TRUE,
  1198. ),
  1199. );
  1200. // Test branch conditions:
  1201. // - No width.
  1202. // - Don't upscale, don't need to upscale.
  1203. $tests[] = array(
  1204. 'input' => array(
  1205. 'dimensions' => array(
  1206. 'width' => 1000,
  1207. 'height' => 800,
  1208. ),
  1209. 'width' => NULL,
  1210. 'height' => 140,
  1211. 'upscale' => FALSE,
  1212. ),
  1213. 'output' => array(
  1214. 'dimensions' => array(
  1215. 'width' => 175,
  1216. 'height' => 140,
  1217. ),
  1218. 'return_value' => TRUE,
  1219. ),
  1220. );
  1221. // Test branch conditions:
  1222. // - Source aspect ratio greater than target.
  1223. // - Upscale, need to upscale.
  1224. $tests[] = array(
  1225. 'input' => array(
  1226. 'dimensions' => array(
  1227. 'width' => 8,
  1228. 'height' => 20,
  1229. ),
  1230. 'width' => 200,
  1231. 'height' => 140,
  1232. 'upscale' => TRUE,
  1233. ),
  1234. 'output' => array(
  1235. 'dimensions' => array(
  1236. 'width' => 56,
  1237. 'height' => 140,
  1238. ),
  1239. 'return_value' => TRUE,
  1240. ),
  1241. );
  1242. // Test branch condition: target aspect ratio greater than source.
  1243. $tests[] = array(
  1244. 'input' => array(
  1245. 'dimensions' => array(
  1246. 'width' => 2000,
  1247. 'height' => 800,
  1248. ),
  1249. 'width' => 200,
  1250. 'height' => 140,
  1251. 'upscale' => FALSE,
  1252. ),
  1253. 'output' => array(
  1254. 'dimensions' => array(
  1255. 'width' => 200,
  1256. 'height' => 80,
  1257. ),
  1258. 'return_value' => TRUE,
  1259. ),
  1260. );
  1261. // Test branch condition: don't upscale, need to upscale.
  1262. $tests[] = array(
  1263. 'input' => array(
  1264. 'dimensions' => array(
  1265. 'width' => 100,
  1266. 'height' => 50,
  1267. ),
  1268. 'width' => 200,
  1269. 'height' => 140,
  1270. 'upscale' => FALSE,
  1271. ),
  1272. 'output' => array(
  1273. 'dimensions' => array(
  1274. 'width' => 100,
  1275. 'height' => 50,
  1276. ),
  1277. 'return_value' => FALSE,
  1278. ),
  1279. );
  1280. foreach ($tests as $test) {
  1281. // Process the test dataset.
  1282. $return_value = image_dimensions_scale($test['input']['dimensions'], $test['input']['width'], $test['input']['height'], $test['input']['upscale']);
  1283. // Check the width.
  1284. $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'])));
  1285. // Check the height.
  1286. $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'])));
  1287. // Check the return value.
  1288. $this->assertEqual($test['output']['return_value'], $return_value, 'Correct return value.');
  1289. }
  1290. }
  1291. }
  1292. /**
  1293. * Tests default image settings.
  1294. */
  1295. class ImageFieldDefaultImagesTestCase extends ImageFieldTestCase {
  1296. public static function getInfo() {
  1297. return array(
  1298. 'name' => 'Image field default images tests',
  1299. 'description' => 'Tests setting up default images both to the field and field instance.',
  1300. 'group' => 'Image',
  1301. );
  1302. }
  1303. function setUp() {
  1304. parent::setUp(array('field_ui'));
  1305. }
  1306. /**
  1307. * Tests CRUD for fields and fields instances with default images.
  1308. */
  1309. function testDefaultImages() {
  1310. // Create files to use as the default images.
  1311. $files = $this->drupalGetTestFiles('image');
  1312. $default_images = array();
  1313. foreach (array('field', 'instance', 'instance2', 'field_new', 'instance_new') as $image_target) {
  1314. $file = array_pop($files);
  1315. $file = file_save($file);
  1316. $default_images[$image_target] = $file;
  1317. }
  1318. // Create an image field and add an instance to the article content type.
  1319. $field_name = strtolower($this->randomName());
  1320. $field_settings = array(
  1321. 'default_image' => $default_images['field']->fid,
  1322. );
  1323. $instance_settings = array(
  1324. 'default_image' => $default_images['instance']->fid,
  1325. );
  1326. $widget_settings = array(
  1327. 'preview_image_style' => 'medium',
  1328. );
  1329. $this->createImageField($field_name, 'article', $field_settings, $instance_settings, $widget_settings);
  1330. $field = field_info_field($field_name);
  1331. $instance = field_info_instance('node', $field_name, 'article');
  1332. // Add another instance with another default image to the page content type.
  1333. $instance2 = array_merge($instance, array(
  1334. 'bundle' => 'page',
  1335. 'settings' => array(
  1336. 'default_image' => $default_images['instance2']->fid,
  1337. ),
  1338. ));
  1339. field_create_instance($instance2);
  1340. $instance2 = field_info_instance('node', $field_name, 'page');
  1341. // Confirm the defaults are present on the article field admin form.
  1342. $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
  1343. $this->assertFieldByXpath(
  1344. '//input[@name="field[settings][default_image][fid]"]',
  1345. $default_images['field']->fid,
  1346. format_string(
  1347. 'Article image field default equals expected file ID of @fid.',
  1348. array('@fid' => $default_images['field']->fid)
  1349. )
  1350. );
  1351. $this->assertFieldByXpath(
  1352. '//input[@name="instance[settings][default_image][fid]"]',
  1353. $default_images['instance']->fid,
  1354. format_string(
  1355. 'Article image field instance default equals expected file ID of @fid.',
  1356. array('@fid' => $default_images['instance']->fid)
  1357. )
  1358. );
  1359. // Confirm the defaults are present on the page field admin form.
  1360. $this->drupalGet("admin/structure/types/manage/page/fields/$field_name");
  1361. $this->assertFieldByXpath(
  1362. '//input[@name="field[settings][default_image][fid]"]',
  1363. $default_images['field']->fid,
  1364. format_string(
  1365. 'Page image field default equals expected file ID of @fid.',
  1366. array('@fid' => $default_images['field']->fid)
  1367. )
  1368. );
  1369. $this->assertFieldByXpath(
  1370. '//input[@name="instance[settings][default_image][fid]"]',
  1371. $default_images['instance2']->fid,
  1372. format_string(
  1373. 'Page image field instance default equals expected file ID of @fid.',
  1374. array('@fid' => $default_images['instance2']->fid)
  1375. )
  1376. );
  1377. // Confirm that the image default is shown for a new article node.
  1378. $article = $this->drupalCreateNode(array('type' => 'article'));
  1379. $article_built = node_view($article);
  1380. $this->assertEqual(
  1381. $article_built[$field_name]['#items'][0]['fid'],
  1382. $default_images['instance']->fid,
  1383. format_string(
  1384. 'A new article node without an image has the expected default image file ID of @fid.',
  1385. array('@fid' => $default_images['instance']->fid)
  1386. )
  1387. );
  1388. // Confirm that the image default is shown for a new page node.
  1389. $page = $this->drupalCreateNode(array('type' => 'page'));
  1390. $page_built = node_view($page);
  1391. $this->assertEqual(
  1392. $page_built[$field_name]['#items'][0]['fid'],
  1393. $default_images['instance2']->fid,
  1394. format_string(
  1395. 'A new page node without an image has the expected default image file ID of @fid.',
  1396. array('@fid' => $default_images['instance2']->fid)
  1397. )
  1398. );
  1399. // Upload a new default for the field.
  1400. $field['settings']['default_image'] = $default_images['field_new']->fid;
  1401. field_update_field($field);
  1402. // Confirm that the new field default is used on the article admin form.
  1403. $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
  1404. $this->assertFieldByXpath(
  1405. '//input[@name="field[settings][default_image][fid]"]',
  1406. $default_images['field_new']->fid,
  1407. format_string(
  1408. 'Updated image field default equals expected file ID of @fid.',
  1409. array('@fid' => $default_images['field_new']->fid)
  1410. )
  1411. );
  1412. // Reload the nodes and confirm the field instance defaults are used.
  1413. $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
  1414. $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
  1415. $this->assertEqual(
  1416. $article_built[$field_name]['#items'][0]['fid'],
  1417. $default_images['instance']->fid,
  1418. format_string(
  1419. 'An existing article node without an image has the expected default image file ID of @fid.',
  1420. array('@fid' => $default_images['instance']->fid)
  1421. )
  1422. );
  1423. $this->assertEqual(
  1424. $page_built[$field_name]['#items'][0]['fid'],
  1425. $default_images['instance2']->fid,
  1426. format_string(
  1427. 'An existing page node without an image has the expected default image file ID of @fid.',
  1428. array('@fid' => $default_images['instance2']->fid)
  1429. )
  1430. );
  1431. // Upload a new default for the article's field instance.
  1432. $instance['settings']['default_image'] = $default_images['instance_new']->fid;
  1433. field_update_instance($instance);
  1434. // Confirm the new field instance default is used on the article field
  1435. // admin form.
  1436. $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
  1437. $this->assertFieldByXpath(
  1438. '//input[@name="instance[settings][default_image][fid]"]',
  1439. $default_images['instance_new']->fid,
  1440. format_string(
  1441. 'Updated article image field instance default equals expected file ID of @fid.',
  1442. array('@fid' => $default_images['instance_new']->fid)
  1443. )
  1444. );
  1445. // Reload the nodes.
  1446. $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
  1447. $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
  1448. // Confirm the article uses the new default.
  1449. $this->assertEqual(
  1450. $article_built[$field_name]['#items'][0]['fid'],
  1451. $default_images['instance_new']->fid,
  1452. format_string(
  1453. 'An existing article node without an image has the expected default image file ID of @fid.',
  1454. array('@fid' => $default_images['instance_new']->fid)
  1455. )
  1456. );
  1457. // Confirm the page remains unchanged.
  1458. $this->assertEqual(
  1459. $page_built[$field_name]['#items'][0]['fid'],
  1460. $default_images['instance2']->fid,
  1461. format_string(
  1462. 'An existing page node without an image has the expected default image file ID of @fid.',
  1463. array('@fid' => $default_images['instance2']->fid)
  1464. )
  1465. );
  1466. // Remove the instance default from articles.
  1467. $instance['settings']['default_image'] = NULL;
  1468. field_update_instance($instance);
  1469. // Confirm the article field instance default has been removed.
  1470. $this->drupalGet("admin/structure/types/manage/article/fields/$field_name");
  1471. $this->assertFieldByXpath(
  1472. '//input[@name="instance[settings][default_image][fid]"]',
  1473. '',
  1474. 'Updated article image field instance default has been successfully removed.'
  1475. );
  1476. // Reload the nodes.
  1477. $article_built = node_view($article = node_load($article->nid, NULL, $reset = TRUE));
  1478. $page_built = node_view($page = node_load($page->nid, NULL, $reset = TRUE));
  1479. // Confirm the article uses the new field (not instance) default.
  1480. $this->assertEqual(
  1481. $article_built[$field_name]['#items'][0]['fid'],
  1482. $default_images['field_new']->fid,
  1483. format_string(
  1484. 'An existing article node without an image has the expected default image file ID of @fid.',
  1485. array('@fid' => $default_images['field_new']->fid)
  1486. )
  1487. );
  1488. // Confirm the page remains unchanged.
  1489. $this->assertEqual(
  1490. $page_built[$field_name]['#items'][0]['fid'],
  1491. $default_images['instance2']->fid,
  1492. format_string(
  1493. 'An existing page node without an image has the expected default image file ID of @fid.',
  1494. array('@fid' => $default_images['instance2']->fid)
  1495. )
  1496. );
  1497. }
  1498. }
  1499. /**
  1500. * Tests image theme functions.
  1501. */
  1502. class ImageThemeFunctionWebTestCase extends DrupalWebTestCase {
  1503. public static function getInfo() {
  1504. return array(
  1505. 'name' => 'Image theme functions',
  1506. 'description' => 'Test that the image theme functions work correctly.',
  1507. 'group' => 'Image',
  1508. );
  1509. }
  1510. function setUp() {
  1511. parent::setUp(array('image'));
  1512. }
  1513. /**
  1514. * Tests usage of the image field formatters.
  1515. */
  1516. function testImageFormatterTheme() {
  1517. // Create an image.
  1518. $files = $this->drupalGetTestFiles('image');
  1519. $file = reset($files);
  1520. $original_uri = file_unmanaged_copy($file->uri, 'public://', FILE_EXISTS_RENAME);
  1521. // Create a style.
  1522. image_style_save(array('name' => 'test', 'label' => 'Test'));
  1523. $url = image_style_url('test', $original_uri);
  1524. // Test using theme_image_formatter() without an image title, alt text, or
  1525. // link options.
  1526. $path = $this->randomName();
  1527. $element = array(
  1528. '#theme' => 'image_formatter',
  1529. '#image_style' => 'test',
  1530. '#item' => array(
  1531. 'uri' => $original_uri,
  1532. ),
  1533. '#path' => array(
  1534. 'path' => $path,
  1535. ),
  1536. );
  1537. $rendered_element = render($element);
  1538. $expected_result = '<a href="' . url($path) . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
  1539. $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders without title, alt, or path options.');
  1540. // Link the image to a fragment on the page, and not a full URL.
  1541. $fragment = $this->randomName();
  1542. $element['#path']['path'] = '';
  1543. $element['#path']['options'] = array(
  1544. 'external' => TRUE,
  1545. 'fragment' => $fragment,
  1546. );
  1547. $rendered_element = render($element);
  1548. $expected_result = '<a href="#' . $fragment . '"><img typeof="foaf:Image" src="' . check_plain($url) . '" alt="" /></a>';
  1549. $this->assertEqual($expected_result, $rendered_element, 'theme_image_formatter() correctly renders a link fragment.');
  1550. }
  1551. }
  1552. /**
  1553. * Tests flushing of image styles.
  1554. */
  1555. class ImageStyleFlushTest extends ImageFieldTestCase {
  1556. public static function getInfo() {
  1557. return array(
  1558. 'name' => 'Image style flushing',
  1559. 'description' => 'Tests flushing of image styles.',
  1560. 'group' => 'Image',
  1561. );
  1562. }
  1563. /**
  1564. * Given an image style and a wrapper, generate an image.
  1565. */
  1566. function createSampleImage($style, $wrapper) {
  1567. static $file;
  1568. if (!isset($file)) {
  1569. $files = $this->drupalGetTestFiles('image');
  1570. $file = reset($files);
  1571. }
  1572. // Make sure we have an image in our wrapper testing file directory.
  1573. $source_uri = file_unmanaged_copy($file->uri, $wrapper . '://');
  1574. // Build the derivative image.
  1575. $derivative_uri = image_style_path($style['name'], $source_uri);
  1576. $derivative = image_style_create_derivative($style, $source_uri, $derivative_uri);
  1577. return $derivative ? $derivative_uri : FALSE;
  1578. }
  1579. /**
  1580. * Count the number of images currently created for a style in a wrapper.
  1581. */
  1582. function getImageCount($style, $wrapper) {
  1583. return count(file_scan_directory($wrapper . '://styles/' . $style['name'], '/.*/'));
  1584. }
  1585. /**
  1586. * General test to flush a style.
  1587. */
  1588. function testFlush() {
  1589. // Setup a style to be created and effects to add to it.
  1590. $style_name = strtolower($this->randomName(10));
  1591. $style_label = $this->randomString();
  1592. $style_path = 'admin/config/media/image-styles/edit/' . $style_name;
  1593. $effect_edits = array(
  1594. 'image_resize' => array(
  1595. 'data[width]' => 100,
  1596. 'data[height]' => 101,
  1597. ),
  1598. 'image_scale' => array(
  1599. 'data[width]' => 110,
  1600. 'data[height]' => 111,
  1601. 'data[upscale]' => 1,
  1602. ),
  1603. );
  1604. // Add style form.
  1605. $edit = array(
  1606. 'name' => $style_name,
  1607. 'label' => $style_label,
  1608. );
  1609. $this->drupalPost('admin/config/media/image-styles/add', $edit, t('Create new style'));
  1610. // Add each sample effect to the style.
  1611. foreach ($effect_edits as $effect => $edit) {
  1612. // Add the effect.
  1613. $this->drupalPost($style_path, array('new' => $effect), t('Add'));
  1614. if (!empty($edit)) {
  1615. $this->drupalPost(NULL, $edit, t('Add effect'));
  1616. }
  1617. }
  1618. // Load the saved image style.
  1619. $style = image_style_load($style_name);
  1620. // Create an image for the 'public' wrapper.
  1621. $image_path = $this->createSampleImage($style, 'public');
  1622. // Expecting to find 2 images, one is the sample.png image shown in
  1623. // image style preview.
  1624. $this->assertEqual($this->getImageCount($style, 'public'), 2, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
  1625. // Create an image for the 'private' wrapper.
  1626. $image_path = $this->createSampleImage($style, 'private');
  1627. $this->assertEqual($this->getImageCount($style, 'private'), 1, format_string('Image style %style image %file successfully generated.', array('%style' => $style['name'], '%file' => $image_path)));
  1628. // Remove the 'image_scale' effect and updates the style, which in turn
  1629. // forces an image style flush.
  1630. $effect = array_pop($style['effects']);
  1631. $this->drupalPost($style_path . '/effects/' . $effect['ieid'] . '/delete', array(), t('Delete'));
  1632. $this->assertResponse(200);
  1633. $this->drupalPost($style_path, array(), t('Update style'));
  1634. $this->assertResponse(200);
  1635. // Post flush, expected 1 image in the 'public' wrapper (sample.png).
  1636. $this->assertEqual($this->getImageCount($style, 'public'), 1, format_string('Image style %style flushed correctly for %wrapper wrapper.', array('%style' => $style['name'], '%wrapper' => 'public')));
  1637. // Post flush, expected no image in the 'private' wrapper.
  1638. $this->assertEqual($this->getImageCount($style, 'private'), 0, format_string('Image style %style flushed correctly for %wrapper wrapper.', array('%style' => $style['name'], '%wrapper' => 'private')));
  1639. }
  1640. }