3 namespace Drupal\Tests\image\Functional;
5 use Drupal\Core\Field\FieldStorageDefinitionInterface;
6 use Drupal\field\Entity\FieldStorageConfig;
7 use Drupal\Tests\TestFileCreationTrait;
8 use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
9 use Drupal\user\RoleInterface;
10 use Drupal\image\Entity\ImageStyle;
13 * Tests the display of image fields.
17 class ImageFieldDisplayTest extends ImageFieldTestBase {
19 use AssertPageCacheContextsAndTagsTrait;
20 use TestFileCreationTrait {
21 getTestFiles as drupalGetTestFiles;
22 compareFiles as drupalCompareFiles;
25 protected $dumpHeaders = TRUE;
32 public static $modules = ['field_ui'];
35 * Test image formatters on node display for public files.
37 public function testImageFieldFormattersPublic() {
38 $this->_testImageFieldFormatters('public');
42 * Test image formatters on node display for private files.
44 public function testImageFieldFormattersPrivate() {
45 // Remove access content permission from anonymous users.
46 user_role_change_permissions(RoleInterface::ANONYMOUS_ID, ['access content' => FALSE]);
47 $this->_testImageFieldFormatters('private');
51 * Test image formatters on node display.
53 public function _testImageFieldFormatters($scheme) {
54 /** @var \Drupal\Core\Render\RendererInterface $renderer */
55 $renderer = $this->container->get('renderer');
56 $node_storage = $this->container->get('entity.manager')->getStorage('node');
57 $field_name = strtolower($this->randomMachineName());
58 $field_settings = ['alt_field_required' => 0];
59 $instance = $this->createImageField($field_name, 'article', ['uri_scheme' => $scheme], $field_settings);
61 // Go to manage display page.
62 $this->drupalGet("admin/structure/types/manage/article/display");
64 // Test for existence of link to image styles configuration.
65 $this->drupalPostForm(NULL, [], "{$field_name}_settings_edit");
66 $this->assertLinkByHref(\Drupal::url('entity.image_style.collection'), 0, 'Link to image styles configuration is found');
68 // Remove 'administer image styles' permission from testing admin user.
69 $admin_user_roles = $this->adminUser->getRoles(TRUE);
70 user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => FALSE]);
72 // Go to manage display page again.
73 $this->drupalGet("admin/structure/types/manage/article/display");
75 // Test for absence of link to image styles configuration.
76 $this->drupalPostForm(NULL, [], "{$field_name}_settings_edit");
77 $this->assertNoLinkByHref(\Drupal::url('entity.image_style.collection'), 'Link to image styles configuration is absent when permissions are insufficient');
79 // Restore 'administer image styles' permission to testing admin user
80 user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
82 // Create a new node with an image attached.
83 $test_image = current($this->drupalGetTestFiles('image'));
85 // Ensure that preview works.
86 $this->previewNodeImage($test_image, $field_name, 'article');
88 // After previewing, make the alt field required. It cannot be required
89 // during preview because the form validation will fail.
90 $instance->setSetting('alt_field_required', 1);
93 // Create alt text for the image.
94 $alt = $this->randomMachineName();
97 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
98 $node_storage->resetCache([$nid]);
99 $node = $node_storage->load($nid);
101 // Test that the default formatter is being used.
102 $file = $node->{$field_name}->entity;
103 $image_uri = $file->getFileUri();
106 '#uri' => $image_uri,
111 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
112 $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
114 // Test the image linked to file formatter.
117 'settings' => ['image_link' => 'file'],
119 $display = entity_get_display('node', $node->getType(), 'default');
120 $display->setComponent($field_name, $display_options)
125 '#uri' => $image_uri,
130 $default_output = '<a href="' . file_create_url($image_uri) . '">' . $renderer->renderRoot($image) . '</a>';
131 $this->drupalGet('node/' . $nid);
132 $this->assertCacheTag($file->getCacheTags()[0]);
133 // @todo Remove in https://www.drupal.org/node/2646744.
134 $this->assertCacheContext('url.site');
135 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
136 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
137 $this->assertRaw($default_output, 'Image linked to file formatter displaying correctly on full node view.');
138 // Verify that the image can be downloaded.
139 $this->assertEqual(file_get_contents($test_image->uri), $this->drupalGet(file_create_url($image_uri)), 'File was downloaded successfully.');
140 if ($scheme == 'private') {
141 // Only verify HTTP headers when using private scheme and the headers are
143 $this->assertEqual($this->drupalGetHeader('Content-Type'), 'image/png', 'Content-Type header was sent.');
144 $this->assertTrue(strstr($this->drupalGetHeader('Cache-Control'), 'private') !== FALSE, 'Cache-Control header was sent.');
146 // Log out and try to access the file.
147 $this->drupalLogout();
148 $this->drupalGet(file_create_url($image_uri));
149 $this->assertResponse('403', 'Access denied to original image as anonymous user.');
152 $this->drupalLogin($this->adminUser);
155 // Test the image linked to content formatter.
156 $display_options['settings']['image_link'] = 'content';
157 $display->setComponent($field_name, $display_options)
161 '#uri' => $image_uri,
165 $this->drupalGet('node/' . $nid);
166 $this->assertCacheTag($file->getCacheTags()[0]);
167 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
168 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
169 $elements = $this->xpath(
170 '//a[@href=:path]/img[@src=:url and @alt=:alt and @width=:width and @height=:height]',
172 ':path' => $node->url(),
173 ':url' => file_url_transform_relative(file_create_url($image['#uri'])),
174 ':width' => $image['#width'],
175 ':height' => $image['#height'],
179 $this->assertEqual(count($elements), 1, 'Image linked to content formatter displaying correctly on full node view.');
181 // Test the image style 'thumbnail' formatter.
182 $display_options['settings']['image_link'] = '';
183 $display_options['settings']['image_style'] = 'thumbnail';
184 $display->setComponent($field_name, $display_options)
187 // Ensure the derivative image is generated so we do not have to deal with
188 // image style callback paths.
189 $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
191 '#theme' => 'image_style',
192 '#uri' => $image_uri,
195 '#style_name' => 'thumbnail',
198 $default_output = $renderer->renderRoot($image_style);
199 $this->drupalGet('node/' . $nid);
200 $image_style = ImageStyle::load('thumbnail');
201 $this->assertCacheTag($image_style->getCacheTags()[0]);
202 $this->assertRaw($default_output, 'Image style thumbnail formatter displaying correctly on full node view.');
204 if ($scheme == 'private') {
205 // Log out and try to access the file.
206 $this->drupalLogout();
207 $this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
208 $this->assertResponse('403', 'Access denied to image style thumbnail as anonymous user.');
211 // Test the image URL formatter without an image style.
213 'type' => 'image_url',
214 'settings' => ['image_style' => ''],
216 $expected_url = file_url_transform_relative(file_create_url($image_uri));
217 $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
219 // Test the image URL formatter with an image style.
220 $display_options['settings']['image_style'] = 'thumbnail';
221 $expected_url = file_url_transform_relative(ImageStyle::load('thumbnail')->buildUrl($image_uri));
222 $this->assertEqual($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
226 * Tests for image field settings.
228 public function testImageFieldSettings() {
229 /** @var \Drupal\Core\Render\RendererInterface $renderer */
230 $renderer = $this->container->get('renderer');
231 $node_storage = $this->container->get('entity.manager')->getStorage('node');
232 $test_image = current($this->drupalGetTestFiles('image'));
233 list(, $test_image_extension) = explode('.', $test_image->filename);
234 $field_name = strtolower($this->randomMachineName());
237 'file_extensions' => $test_image_extension,
238 'max_filesize' => '50 KB',
239 'max_resolution' => '100x100',
240 'min_resolution' => '10x10',
244 'preview_image_style' => 'medium',
246 $field = $this->createImageField($field_name, 'article', [], $field_settings, $widget_settings);
248 // Verify that the min/max resolution set on the field are properly
249 // extracted, and displayed, on the image field's configuration form.
250 $this->drupalGet('admin/structure/types/manage/article/fields/' . $field->id());
251 $this->assertFieldByName('settings[max_resolution][x]', '100', 'Expected max resolution X value of 100.');
252 $this->assertFieldByName('settings[max_resolution][y]', '100', 'Expected max resolution Y value of 100.');
253 $this->assertFieldByName('settings[min_resolution][x]', '10', 'Expected min resolution X value of 10.');
254 $this->assertFieldByName('settings[min_resolution][y]', '10', 'Expected min resolution Y value of 10.');
256 $this->drupalGet('node/add/article');
257 $this->assertText(t('50 KB limit.'), 'Image widget max file size is displayed on article form.');
258 $this->assertText(t('Allowed types: @extensions.', ['@extensions' => $test_image_extension]), 'Image widget allowed file types displayed on article form.');
259 $this->assertText(t('Images must be larger than 10x10 pixels. Images larger than 100x100 pixels will be resized.'), 'Image widget allowed resolution displayed on article form.');
261 // We have to create the article first and then edit it because the alt
262 // and title fields do not display until the image has been attached.
264 // Create alt text for the image.
265 $alt = $this->randomMachineName();
267 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
268 $this->drupalGet('node/' . $nid . '/edit');
270 // Verify that the optional fields alt & title are saved & filled.
271 $this->assertFieldByName($field_name . '[0][alt]', $alt, 'Alt field displayed on article form.');
272 $this->assertFieldByName($field_name . '[0][title]', '', 'Title field displayed on article form.');
274 // Verify that the attached image is being previewed using the 'medium'
276 $node_storage->resetCache([$nid]);
277 $node = $node_storage->load($nid);
278 $file = $node->{$field_name}->entity;
280 $url = file_url_transform_relative(file_create_url(ImageStyle::load('medium')->buildUrl($file->getFileUri())));
281 $this->assertTrue($this->cssSelect('img[width=40][height=20][class=image-style-medium][src="' . $url . '"]'));
283 // Add alt/title fields to the image and verify that they are displayed.
286 '#uri' => $file->getFileUri(),
288 '#title' => $this->randomMachineName(),
293 $field_name . '[0][alt]' => $image['#alt'],
294 $field_name . '[0][title]' => $image['#title'],
296 $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save'));
297 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
298 $this->assertRaw($default_output, 'Image displayed using user supplied alt and title attributes.');
300 // Verify that alt/title longer than allowed results in a validation error.
303 $field_name . '[0][alt]' => $this->randomMachineName($test_size),
304 $field_name . '[0][title]' => $this->randomMachineName($test_size),
306 $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save'));
307 $schema = $field->getFieldStorageDefinition()->getSchema();
308 $this->assertRaw(t('Alternative text cannot be longer than %max characters but is currently %length characters long.', [
309 '%max' => $schema['columns']['alt']['length'],
310 '%length' => $test_size,
312 $this->assertRaw(t('Title cannot be longer than %max characters but is currently %length characters long.', [
313 '%max' => $schema['columns']['title']['length'],
314 '%length' => $test_size,
317 // Set cardinality to unlimited and add upload a second image.
318 // The image widget is extending on the file widget, but the image field
319 // type does not have the 'display_field' setting which is expected by
320 // the file widget. This resulted in notices before when cardinality is not
321 // 1, so we need to make sure the file widget prevents these notices by
322 // providing all settings, even if they are not used.
323 // @see FileWidget::formMultipleElements().
324 $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $field_name . '/storage', ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED], t('Save field settings'));
326 'files[' . $field_name . '_1][]' => \Drupal::service('file_system')->realpath($test_image->uri),
328 $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
329 // Add the required alt text.
330 $this->drupalPostForm(NULL, [$field_name . '[1][alt]' => $alt], t('Save'));
331 $this->assertText(format_string('Article @title has been updated.', ['@title' => $node->getTitle()]));
333 // Assert ImageWidget::process() calls FieldWidget::process().
334 $this->drupalGet('node/' . $node->id() . '/edit');
336 'files[' . $field_name . '_2][]' => \Drupal::service('file_system')->realpath($test_image->uri),
338 $this->drupalPostForm(NULL, $edit, $field_name . '_2_upload_button');
339 $this->assertSession()->elementNotExists('css', 'input[name="files[' . $field_name . '_2][]"]');
340 $this->assertSession()->elementExists('css', 'input[name="files[' . $field_name . '_3][]"]');
344 * Test use of a default image with an image field.
346 public function testImageFieldDefaultImage() {
347 /** @var \Drupal\Core\Render\RendererInterface $renderer */
348 $renderer = $this->container->get('renderer');
350 $node_storage = $this->container->get('entity.manager')->getStorage('node');
351 // Create a new image field.
352 $field_name = strtolower($this->randomMachineName());
353 $this->createImageField($field_name, 'article');
355 // Create a new node, with no images and verify that no images are
357 $node = $this->drupalCreateNode(['type' => 'article']);
358 $this->drupalGet('node/' . $node->id());
359 // Verify that no image is displayed on the page by checking for the class
360 // that would be used on the image field.
361 $this->assertNoPattern('<div class="(.*?)field--name-' . strtr($field_name, '_', '-') . '(.*?)">', 'No image displayed when no image is attached and no default image specified.');
362 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
363 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
365 // Add a default image to the public image field.
366 $images = $this->drupalGetTestFiles('image');
367 $alt = $this->randomString(512);
368 $title = $this->randomString(1024);
370 // Get the path of the 'image-test.png' file.
371 'files[settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($images[0]->uri),
372 'settings[default_image][alt]' => $alt,
373 'settings[default_image][title]' => $title,
375 $this->drupalPostForm("admin/structure/types/manage/article/fields/node.article.$field_name/storage", $edit, t('Save field settings'));
376 // Clear field definition cache so the new default image is detected.
377 \Drupal::entityManager()->clearCachedFieldDefinitions();
378 $field_storage = FieldStorageConfig::loadByName('node', $field_name);
379 $default_image = $field_storage->getSetting('default_image');
380 $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
381 $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
384 '#uri' => $file->getFileUri(),
390 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
391 $this->drupalGet('node/' . $node->id());
392 $this->assertCacheTag($file->getCacheTags()[0]);
393 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
394 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
395 $this->assertRaw($default_output, 'Default image displayed when no user supplied image is present.');
397 // Create a node with an image attached and ensure that the default image
400 // Create alt text for the image.
401 $alt = $this->randomMachineName();
403 // Upload the 'image-test.gif' file.
404 $nid = $this->uploadNodeImage($images[2], $field_name, 'article', $alt);
405 $node_storage->resetCache([$nid]);
406 $node = $node_storage->load($nid);
407 $file = $node->{$field_name}->entity;
410 '#uri' => $file->getFileUri(),
415 $image_output = str_replace("\n", NULL, $renderer->renderRoot($image));
416 $this->drupalGet('node/' . $nid);
417 $this->assertCacheTag($file->getCacheTags()[0]);
418 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
419 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
420 $this->assertNoRaw($default_output, 'Default image is not displayed when user supplied image is present.');
421 $this->assertRaw($image_output, 'User supplied image is displayed.');
423 // Remove default image from the field and make sure it is no longer used.
424 // Can't use fillField cause Mink can't fill hidden fields.
425 $this->drupalGet("admin/structure/types/manage/article/fields/node.article.$field_name/storage");
426 $this->getSession()->getPage()->find('css', 'input[name="settings[default_image][uuid][fids]"]')->setValue(0);
427 $this->getSession()->getPage()->pressButton(t('Save field settings'));
429 // Clear field definition cache so the new default image is detected.
430 \Drupal::entityManager()->clearCachedFieldDefinitions();
431 $field_storage = FieldStorageConfig::loadByName('node', $field_name);
432 $default_image = $field_storage->getSetting('default_image');
433 $this->assertFalse($default_image['uuid'], 'Default image removed from field.');
434 // Create an image field that uses the private:// scheme and test that the
435 // default image works as expected.
436 $private_field_name = strtolower($this->randomMachineName());
437 $this->createImageField($private_field_name, 'article', ['uri_scheme' => 'private']);
438 // Add a default image to the new field.
440 // Get the path of the 'image-test.gif' file.
441 'files[settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($images[2]->uri),
442 'settings[default_image][alt]' => $alt,
443 'settings[default_image][title]' => $title,
445 $this->drupalPostForm('admin/structure/types/manage/article/fields/node.article.' . $private_field_name . '/storage', $edit, t('Save field settings'));
446 // Clear field definition cache so the new default image is detected.
447 \Drupal::entityManager()->clearCachedFieldDefinitions();
449 $private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
450 $default_image = $private_field_storage->getSetting('default_image');
451 $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
452 $this->assertEqual('private', file_uri_scheme($file->getFileUri()), 'Default image uses private:// scheme.');
453 $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
454 // Create a new node with no image attached and ensure that default private
455 // image is displayed.
456 $node = $this->drupalCreateNode(['type' => 'article']);
459 '#uri' => $file->getFileUri(),
465 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
466 $this->drupalGet('node/' . $node->id());
467 $this->assertCacheTag($file->getCacheTags()[0]);
468 $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags');
469 $this->assertTrue(!preg_match('/ image_style\:/', $cache_tags_header), 'No image style cache tag found.');
470 $this->assertRaw($default_output, 'Default private image displayed when no user supplied image is present.');