image.test 76 KB

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