image.test 91 KB

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