comparison core/modules/image/tests/src/Functional/ImageFieldDisplayTest.php @ 16:c2387f117808

Routine composer update
author Chris Cannam
date Tue, 10 Jul 2018 15:07:59 +0100
parents
children af1871eacc83
comparison
equal deleted inserted replaced
15:e200cb7efeb3 16:c2387f117808
1 <?php
2
3 namespace Drupal\Tests\image\Functional;
4
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;
11
12 /**
13 * Tests the display of image fields.
14 *
15 * @group image
16 */
17 class ImageFieldDisplayTest extends ImageFieldTestBase {
18
19 use AssertPageCacheContextsAndTagsTrait;
20 use TestFileCreationTrait {
21 getTestFiles as drupalGetTestFiles;
22 compareFiles as drupalCompareFiles;
23 }
24
25 protected $dumpHeaders = TRUE;
26
27 /**
28 * Modules to enable.
29 *
30 * @var array
31 */
32 public static $modules = ['field_ui'];
33
34 /**
35 * Test image formatters on node display for public files.
36 */
37 public function testImageFieldFormattersPublic() {
38 $this->_testImageFieldFormatters('public');
39 }
40
41 /**
42 * Test image formatters on node display for private files.
43 */
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');
48 }
49
50 /**
51 * Test image formatters on node display.
52 */
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);
60
61 // Go to manage display page.
62 $this->drupalGet("admin/structure/types/manage/article/display");
63
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');
67
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]);
71
72 // Go to manage display page again.
73 $this->drupalGet("admin/structure/types/manage/article/display");
74
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');
78
79 // Restore 'administer image styles' permission to testing admin user
80 user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
81
82 // Create a new node with an image attached.
83 $test_image = current($this->drupalGetTestFiles('image'));
84
85 // Ensure that preview works.
86 $this->previewNodeImage($test_image, $field_name, 'article');
87
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);
91 $instance->save();
92
93 // Create alt text for the image.
94 $alt = $this->randomMachineName();
95
96 // Save node.
97 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
98 $node_storage->resetCache([$nid]);
99 $node = $node_storage->load($nid);
100
101 // Test that the default formatter is being used.
102 $file = $node->{$field_name}->entity;
103 $image_uri = $file->getFileUri();
104 $image = [
105 '#theme' => 'image',
106 '#uri' => $image_uri,
107 '#width' => 40,
108 '#height' => 20,
109 '#alt' => $alt,
110 ];
111 $default_output = str_replace("\n", NULL, $renderer->renderRoot($image));
112 $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
113
114 // Test the image linked to file formatter.
115 $display_options = [
116 'type' => 'image',
117 'settings' => ['image_link' => 'file'],
118 ];
119 $display = entity_get_display('node', $node->getType(), 'default');
120 $display->setComponent($field_name, $display_options)
121 ->save();
122
123 $image = [
124 '#theme' => 'image',
125 '#uri' => $image_uri,
126 '#width' => 40,
127 '#height' => 20,
128 '#alt' => $alt,
129 ];
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
142 // sent by Drupal.
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.');
145
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.');
150
151 // Log in again.
152 $this->drupalLogin($this->adminUser);
153 }
154
155 // Test the image linked to content formatter.
156 $display_options['settings']['image_link'] = 'content';
157 $display->setComponent($field_name, $display_options)
158 ->save();
159 $image = [
160 '#theme' => 'image',
161 '#uri' => $image_uri,
162 '#width' => 40,
163 '#height' => 20,
164 ];
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]',
171 [
172 ':path' => $node->url(),
173 ':url' => file_url_transform_relative(file_create_url($image['#uri'])),
174 ':width' => $image['#width'],
175 ':height' => $image['#height'],
176 ':alt' => $alt,
177 ]
178 );
179 $this->assertEqual(count($elements), 1, 'Image linked to content formatter displaying correctly on full node view.');
180
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)
185 ->save();
186
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));
190 $image_style = [
191 '#theme' => 'image_style',
192 '#uri' => $image_uri,
193 '#width' => 40,
194 '#height' => 20,
195 '#style_name' => 'thumbnail',
196 '#alt' => $alt,
197 ];
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.');
203
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.');
209 }
210
211 // Test the image URL formatter without an image style.
212 $display_options = [
213 'type' => 'image_url',
214 'settings' => ['image_style' => ''],
215 ];
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']);
218
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']);
223 }
224
225 /**
226 * Tests for image field settings.
227 */
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());
235 $field_settings = [
236 'alt_field' => 1,
237 'file_extensions' => $test_image_extension,
238 'max_filesize' => '50 KB',
239 'max_resolution' => '100x100',
240 'min_resolution' => '10x10',
241 'title_field' => 1,
242 ];
243 $widget_settings = [
244 'preview_image_style' => 'medium',
245 ];
246 $field = $this->createImageField($field_name, 'article', [], $field_settings, $widget_settings);
247
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.');
255
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.');
260
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.
263
264 // Create alt text for the image.
265 $alt = $this->randomMachineName();
266
267 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
268 $this->drupalGet('node/' . $nid . '/edit');
269
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.');
273
274 // Verify that the attached image is being previewed using the 'medium'
275 // style.
276 $node_storage->resetCache([$nid]);
277 $node = $node_storage->load($nid);
278 $file = $node->{$field_name}->entity;
279
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 . '"]'));
282
283 // Add alt/title fields to the image and verify that they are displayed.
284 $image = [
285 '#theme' => 'image',
286 '#uri' => $file->getFileUri(),
287 '#alt' => $alt,
288 '#title' => $this->randomMachineName(),
289 '#width' => 40,
290 '#height' => 20,
291 ];
292 $edit = [
293 $field_name . '[0][alt]' => $image['#alt'],
294 $field_name . '[0][title]' => $image['#title'],
295 ];
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.');
299
300 // Verify that alt/title longer than allowed results in a validation error.
301 $test_size = 2000;
302 $edit = [
303 $field_name . '[0][alt]' => $this->randomMachineName($test_size),
304 $field_name . '[0][title]' => $this->randomMachineName($test_size),
305 ];
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,
311 ]));
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,
315 ]));
316
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'));
325 $edit = [
326 'files[' . $field_name . '_1][]' => \Drupal::service('file_system')->realpath($test_image->uri),
327 ];
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()]));
332
333 // Assert ImageWidget::process() calls FieldWidget::process().
334 $this->drupalGet('node/' . $node->id() . '/edit');
335 $edit = [
336 'files[' . $field_name . '_2][]' => \Drupal::service('file_system')->realpath($test_image->uri),
337 ];
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][]"]');
341 }
342
343 /**
344 * Test use of a default image with an image field.
345 */
346 public function testImageFieldDefaultImage() {
347 /** @var \Drupal\Core\Render\RendererInterface $renderer */
348 $renderer = $this->container->get('renderer');
349
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');
354
355 // Create a new node, with no images and verify that no images are
356 // displayed.
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.');
364
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);
369 $edit = [
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,
374 ];
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.');
382 $image = [
383 '#theme' => 'image',
384 '#uri' => $file->getFileUri(),
385 '#alt' => $alt,
386 '#title' => $title,
387 '#width' => 40,
388 '#height' => 20,
389 ];
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.');
396
397 // Create a node with an image attached and ensure that the default image
398 // is not displayed.
399
400 // Create alt text for the image.
401 $alt = $this->randomMachineName();
402
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;
408 $image = [
409 '#theme' => 'image',
410 '#uri' => $file->getFileUri(),
411 '#width' => 40,
412 '#height' => 20,
413 '#alt' => $alt,
414 ];
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.');
422
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'));
428
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.
439 $edit = [
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,
444 ];
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();
448
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']);
457 $image = [
458 '#theme' => 'image',
459 '#uri' => $file->getFileUri(),
460 '#alt' => $alt,
461 '#title' => $title,
462 '#width' => 40,
463 '#height' => 20,
464 ];
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.');
471 }
472
473 }