image.test 70 KB

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