image.test 76 KB

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