image.test 80 KB

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