image.test 77 KB

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