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

Routine composer update
author Chris Cannam
date Tue, 10 Jul 2018 15:07:59 +0100
parents
children 129ea1e6d783
comparison
equal deleted inserted replaced
15:e200cb7efeb3 16:c2387f117808
1 <?php
2
3 namespace Drupal\Tests\image\Functional;
4
5 use Drupal\Component\Utility\SafeMarkup;
6 use Drupal\Core\Entity\Entity\EntityViewDisplay;
7 use Drupal\image\Entity\ImageStyle;
8 use Drupal\image\ImageStyleInterface;
9 use Drupal\node\Entity\Node;
10 use Drupal\file\Entity\File;
11 use Drupal\Tests\TestFileCreationTrait;
12
13 /**
14 * Tests creation, deletion, and editing of image styles and effects.
15 *
16 * @group image
17 */
18 class ImageAdminStylesTest extends ImageFieldTestBase {
19
20 use TestFileCreationTrait {
21 getTestFiles as drupalGetTestFiles;
22 compareFiles as drupalCompareFiles;
23 }
24
25 /**
26 * Given an image style, generate an image.
27 */
28 public function createSampleImage(ImageStyleInterface $style) {
29 static $file_path;
30
31 // First, we need to make sure we have an image in our testing
32 // file directory. Copy over an image on the first run.
33 if (!isset($file_path)) {
34 $files = $this->drupalGetTestFiles('image');
35 $file = reset($files);
36 $file_path = file_unmanaged_copy($file->uri);
37 }
38
39 return $style->buildUrl($file_path) ? $file_path : FALSE;
40 }
41
42 /**
43 * Count the number of images currently create for a style.
44 */
45 public function getImageCount(ImageStyleInterface $style) {
46 return count(file_scan_directory('public://styles/' . $style->id(), '/.*/'));
47 }
48
49 /**
50 * Test creating an image style with a numeric name and ensuring it can be
51 * applied to an image.
52 */
53 public function testNumericStyleName() {
54 $style_name = rand();
55 $style_label = $this->randomString();
56 $edit = [
57 'name' => $style_name,
58 'label' => $style_label,
59 ];
60 $this->drupalPostForm('admin/config/media/image-styles/add', $edit, t('Create new style'));
61 $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
62 $options = image_style_options();
63 $this->assertTrue(array_key_exists($style_name, $options), format_string('Array key %key exists.', ['%key' => $style_name]));
64 }
65
66 /**
67 * General test to add a style, add/remove/edit effects to it, then delete it.
68 */
69 public function testStyle() {
70 $admin_path = 'admin/config/media/image-styles';
71
72 // Setup a style to be created and effects to add to it.
73 $style_name = strtolower($this->randomMachineName(10));
74 $style_label = $this->randomString();
75 $style_path = $admin_path . '/manage/' . $style_name;
76 $effect_edits = [
77 'image_resize' => [
78 'width' => 100,
79 'height' => 101,
80 ],
81 'image_scale' => [
82 'width' => 110,
83 'height' => 111,
84 'upscale' => 1,
85 ],
86 'image_scale_and_crop' => [
87 'width' => 120,
88 'height' => 121,
89 ],
90 'image_crop' => [
91 'width' => 130,
92 'height' => 131,
93 'anchor' => 'left-top',
94 ],
95 'image_desaturate' => [
96 // No options for desaturate.
97 ],
98 'image_rotate' => [
99 'degrees' => 5,
100 'random' => 1,
101 'bgcolor' => '#FFFF00',
102 ],
103 ];
104
105 // Add style form.
106
107 $edit = [
108 'name' => $style_name,
109 'label' => $style_label,
110 ];
111 $this->drupalPostForm($admin_path . '/add', $edit, t('Create new style'));
112 $this->assertRaw(t('Style %name was created.', ['%name' => $style_label]));
113
114 // Ensure that the expected entity operations are there.
115 $this->drupalGet($admin_path);
116 $this->assertLinkByHref($style_path);
117 $this->assertLinkByHref($style_path . '/flush');
118 $this->assertLinkByHref($style_path . '/delete');
119
120 // Add effect form.
121
122 // Add each sample effect to the style.
123 foreach ($effect_edits as $effect => $edit) {
124 $edit_data = [];
125 foreach ($edit as $field => $value) {
126 $edit_data['data[' . $field . ']'] = $value;
127 }
128 // Add the effect.
129 $this->drupalPostForm($style_path, ['new' => $effect], t('Add'));
130 if (!empty($edit)) {
131 $this->drupalPostForm(NULL, $edit_data, t('Add effect'));
132 }
133 }
134
135 // Load the saved image style.
136 $style = ImageStyle::load($style_name);
137
138 // Ensure that third party settings were added to the config entity.
139 // These are added by a hook_image_style_presave() implemented in
140 // image_module_test module.
141 $this->assertEqual('bar', $style->getThirdPartySetting('image_module_test', 'foo'), 'Third party settings were added to the image style.');
142
143 // Ensure that the image style URI matches our expected path.
144 $style_uri_path = $style->url();
145 $this->assertTrue(strpos($style_uri_path, $style_path) !== FALSE, 'The image style URI is correct.');
146
147 // Confirm that all effects on the image style have settings that match
148 // what was saved.
149 $uuids = [];
150 foreach ($style->getEffects() as $uuid => $effect) {
151 // Store the uuid for later use.
152 $uuids[$effect->getPluginId()] = $uuid;
153 $effect_configuration = $effect->getConfiguration();
154 foreach ($effect_edits[$effect->getPluginId()] as $field => $value) {
155 $this->assertEqual($value, $effect_configuration['data'][$field], SafeMarkup::format('The %field field in the %effect effect has the correct value of %value.', ['%field' => $field, '%effect' => $effect->getPluginId(), '%value' => $value]));
156 }
157 }
158
159 // Assert that every effect was saved.
160 foreach (array_keys($effect_edits) as $effect_name) {
161 $this->assertTrue(isset($uuids[$effect_name]), format_string(
162 'A %effect_name effect was saved with ID %uuid',
163 [
164 '%effect_name' => $effect_name,
165 '%uuid' => $uuids[$effect_name],
166 ]));
167 }
168
169 // Image style overview form (ordering and renaming).
170
171 // Confirm the order of effects is maintained according to the order we
172 // added the fields.
173 $effect_edits_order = array_keys($effect_edits);
174 $order_correct = TRUE;
175 $index = 0;
176 foreach ($style->getEffects() as $effect) {
177 if ($effect_edits_order[$index] != $effect->getPluginId()) {
178 $order_correct = FALSE;
179 }
180 $index++;
181 }
182 $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
183
184 // Test the style overview form.
185 // Change the name of the style and adjust the weights of effects.
186 $style_name = strtolower($this->randomMachineName(10));
187 $style_label = $this->randomMachineName();
188 $weight = count($effect_edits);
189 $edit = [
190 'name' => $style_name,
191 'label' => $style_label,
192 ];
193 foreach ($style->getEffects() as $uuid => $effect) {
194 $edit['effects[' . $uuid . '][weight]'] = $weight;
195 $weight--;
196 }
197
198 // Create an image to make sure it gets flushed after saving.
199 $image_path = $this->createSampleImage($style);
200 $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));
201
202 $this->drupalPostForm($style_path, $edit, t('Update style'));
203
204 // Note that after changing the style name, the style path is changed.
205 $style_path = 'admin/config/media/image-styles/manage/' . $style_name;
206
207 // Check that the URL was updated.
208 $this->drupalGet($style_path);
209 $this->assertTitle(t('Edit style @name | Drupal', ['@name' => $style_label]));
210 $this->assertResponse(200, format_string('Image style %original renamed to %new', ['%original' => $style->id(), '%new' => $style_name]));
211
212 // Check that the available image effects are properly sorted.
213 $option = $this->xpath('//select[@id=:id]//option', [':id' => 'edit-new--2']);
214 $this->assertEquals('Ajax test', $option[1]->getText(), '"Ajax test" is the first selectable effect.');
215
216 // Check that the image was flushed after updating the style.
217 // This is especially important when renaming the style. Make sure that
218 // the old image directory has been deleted.
219 $this->assertEqual($this->getImageCount($style), 0, format_string('Image style %style was flushed after renaming the style and updating the order of effects.', ['%style' => $style->label()]));
220
221 // Load the style by the new name with the new weights.
222 $style = ImageStyle::load($style_name);
223
224 // Confirm the new style order was saved.
225 $effect_edits_order = array_reverse($effect_edits_order);
226 $order_correct = TRUE;
227 $index = 0;
228 foreach ($style->getEffects() as $effect) {
229 if ($effect_edits_order[$index] != $effect->getPluginId()) {
230 $order_correct = FALSE;
231 }
232 $index++;
233 }
234 $this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
235
236 // Image effect deletion form.
237
238 // Create an image to make sure it gets flushed after deleting an effect.
239 $image_path = $this->createSampleImage($style);
240 $this->assertEqual($this->getImageCount($style), 1, format_string('Image style %style image %file successfully generated.', ['%style' => $style->label(), '%file' => $image_path]));
241
242 // Delete the 'image_crop' effect from the style.
243 $this->drupalPostForm($style_path . '/effects/' . $uuids['image_crop'] . '/delete', [], t('Delete'));
244 // Confirm that the form submission was successful.
245 $this->assertResponse(200);
246 $image_crop_effect = $style->getEffect($uuids['image_crop']);
247 $this->assertRaw(t('The image effect %name has been deleted.', ['%name' => $image_crop_effect->label()]));
248 // Confirm that there is no longer a link to the effect.
249 $this->assertNoLinkByHref($style_path . '/effects/' . $uuids['image_crop'] . '/delete');
250 // Refresh the image style information and verify that the effect was
251 // actually deleted.
252 $entity_type_manager = $this->container->get('entity_type.manager');
253 $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style->id());
254 $this->assertFalse($style->getEffects()->has($uuids['image_crop']), format_string(
255 'Effect with ID %uuid no longer found on image style %style',
256 [
257 '%uuid' => $uuids['image_crop'],
258 '%style' => $style->label(),
259 ]));
260
261 // Additional test on Rotate effect, for transparent background.
262 $edit = [
263 'data[degrees]' => 5,
264 'data[random]' => 0,
265 'data[bgcolor]' => '',
266 ];
267 $this->drupalPostForm($style_path, ['new' => 'image_rotate'], t('Add'));
268 $this->drupalPostForm(NULL, $edit, t('Add effect'));
269 $entity_type_manager = $this->container->get('entity_type.manager');
270 $style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style_name);
271 $this->assertEqual(count($style->getEffects()), 6, 'Rotate effect with transparent background was added.');
272
273 // Style deletion form.
274
275 // Delete the style.
276 $this->drupalPostForm($style_path . '/delete', [], t('Delete'));
277
278 // Confirm the style directory has been removed.
279 $directory = file_default_scheme() . '://styles/' . $style_name;
280 $this->assertFalse(is_dir($directory), format_string('Image style %style directory removed on style deletion.', ['%style' => $style->label()]));
281
282 $this->assertFalse(ImageStyle::load($style_name), format_string('Image style %style successfully deleted.', ['%style' => $style->label()]));
283
284 // Test empty text when there are no image styles.
285
286 // Delete all image styles.
287 foreach (ImageStyle::loadMultiple() as $image_style) {
288 $image_style->delete();
289 }
290
291 // Confirm that the empty text is correct on the image styles page.
292 $this->drupalGet($admin_path);
293 $this->assertRaw(t('There are currently no styles. <a href=":url">Add a new one</a>.', [
294 ':url' => \Drupal::url('image.style_add'),
295 ]));
296
297 }
298
299 /**
300 * Test deleting a style and choosing a replacement style.
301 */
302 public function testStyleReplacement() {
303 // Create a new style.
304 $style_name = strtolower($this->randomMachineName(10));
305 $style_label = $this->randomString();
306 $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
307 $style->save();
308 $style_path = 'admin/config/media/image-styles/manage/';
309
310 // Create an image field that uses the new style.
311 $field_name = strtolower($this->randomMachineName(10));
312 $this->createImageField($field_name, 'article');
313 entity_get_display('node', 'article', 'default')
314 ->setComponent($field_name, [
315 'type' => 'image',
316 'settings' => ['image_style' => $style_name],
317 ])
318 ->save();
319
320 // Create a new node with an image attached.
321 $test_image = current($this->drupalGetTestFiles('image'));
322 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
323 $node = Node::load($nid);
324
325 // Get node field original image URI.
326 $fid = $node->get($field_name)->target_id;
327 $original_uri = File::load($fid)->getFileUri();
328
329 // Test that image is displayed using newly created style.
330 $this->drupalGet('node/' . $nid);
331 $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
332
333 // Rename the style and make sure the image field is updated.
334 $new_style_name = strtolower($this->randomMachineName(10));
335 $new_style_label = $this->randomString();
336 $edit = [
337 'name' => $new_style_name,
338 'label' => $new_style_label,
339 ];
340 $this->drupalPostForm($style_path . $style_name, $edit, t('Update style'));
341 $this->assertText(t('Changes to the style have been saved.'), format_string('Style %name was renamed to %new_name.', ['%name' => $style_name, '%new_name' => $new_style_name]));
342 $this->drupalGet('node/' . $nid);
343
344 // Reload the image style using the new name.
345 $style = ImageStyle::load($new_style_name);
346 $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
347
348 // Delete the style and choose a replacement style.
349 $edit = [
350 'replacement' => 'thumbnail',
351 ];
352 $this->drupalPostForm($style_path . $new_style_name . '/delete', $edit, t('Delete'));
353 $message = t('The image style %name has been deleted.', ['%name' => $new_style_label]);
354 $this->assertRaw($message);
355
356 $replacement_style = ImageStyle::load('thumbnail');
357 $this->drupalGet('node/' . $nid);
358 $this->assertRaw(file_url_transform_relative($replacement_style->buildUrl($original_uri)), 'Image displayed using style replacement style.');
359 }
360
361 /**
362 * Verifies that editing an image effect does not cause it to be duplicated.
363 */
364 public function testEditEffect() {
365 // Add a scale effect.
366 $style_name = 'test_style_effect_edit';
367 $this->drupalGet('admin/config/media/image-styles/add');
368 $this->drupalPostForm(NULL, ['label' => 'Test style effect edit', 'name' => $style_name], t('Create new style'));
369 $this->drupalPostForm(NULL, ['new' => 'image_scale_and_crop'], t('Add'));
370 $this->drupalPostForm(NULL, ['data[width]' => '300', 'data[height]' => '200'], t('Add effect'));
371 $this->assertText(t('Scale and crop 300×200'));
372
373 // There should normally be only one edit link on this page initially.
374 $this->clickLink(t('Edit'));
375 $this->drupalPostForm(NULL, ['data[width]' => '360', 'data[height]' => '240'], t('Update effect'));
376 $this->assertText(t('Scale and crop 360×240'));
377
378 // Check that the previous effect is replaced.
379 $this->assertNoText(t('Scale and crop 300×200'));
380
381 // Add another scale effect.
382 $this->drupalGet('admin/config/media/image-styles/add');
383 $this->drupalPostForm(NULL, ['label' => 'Test style scale edit scale', 'name' => 'test_style_scale_edit_scale'], t('Create new style'));
384 $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
385 $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
386
387 // Edit the scale effect that was just added.
388 $this->clickLink(t('Edit'));
389 $this->drupalPostForm(NULL, ['data[width]' => '24', 'data[height]' => '19'], t('Update effect'));
390
391 // Add another scale effect and make sure both exist. Click through from
392 // the overview to make sure that it is possible to add new effect then.
393 $this->drupalGet('admin/config/media/image-styles');
394 $rows = $this->xpath('//table/tbody/tr');
395 $i = 0;
396 foreach ($rows as $row) {
397 if ($row->find('css', 'td')->getText() === 'Test style scale edit scale') {
398 $this->clickLink('Edit', $i);
399 break;
400 }
401 $i++;
402 }
403 $this->drupalPostForm(NULL, ['new' => 'image_scale'], t('Add'));
404 $this->drupalPostForm(NULL, ['data[width]' => '12', 'data[height]' => '19'], t('Add effect'));
405 $this->assertText(t('Scale 24×19'));
406 $this->assertText(t('Scale 12×19'));
407
408 // Try to edit a nonexistent effect.
409 $uuid = $this->container->get('uuid');
410 $this->drupalGet('admin/config/media/image-styles/manage/' . $style_name . '/effects/' . $uuid->generate());
411 $this->assertResponse(404);
412 }
413
414 /**
415 * Test flush user interface.
416 */
417 public function testFlushUserInterface() {
418 $admin_path = 'admin/config/media/image-styles';
419
420 // Create a new style.
421 $style_name = strtolower($this->randomMachineName(10));
422 $style = ImageStyle::create(['name' => $style_name, 'label' => $this->randomString()]);
423 $style->save();
424
425 // Create an image to make sure it gets flushed.
426 $files = $this->drupalGetTestFiles('image');
427 $image_uri = $files[0]->uri;
428 $derivative_uri = $style->buildUri($image_uri);
429 $this->assertTrue($style->createDerivative($image_uri, $derivative_uri));
430 $this->assertEqual($this->getImageCount($style), 1);
431
432 // Go to image styles list page and check if the flush operation link
433 // exists.
434 $this->drupalGet($admin_path);
435 $flush_path = $admin_path . '/manage/' . $style_name . '/flush';
436 $this->assertLinkByHref($flush_path);
437
438 // Flush the image style derivatives using the user interface.
439 $this->drupalPostForm($flush_path, [], t('Flush'));
440
441 // The derivative image file should have been deleted.
442 $this->assertEqual($this->getImageCount($style), 0);
443 }
444
445 /**
446 * Tests image style configuration import that does a delete.
447 */
448 public function testConfigImport() {
449 // Create a new style.
450 $style_name = strtolower($this->randomMachineName(10));
451 $style_label = $this->randomString();
452 $style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
453 $style->save();
454
455 // Create an image field that uses the new style.
456 $field_name = strtolower($this->randomMachineName(10));
457 $this->createImageField($field_name, 'article');
458 entity_get_display('node', 'article', 'default')
459 ->setComponent($field_name, [
460 'type' => 'image',
461 'settings' => ['image_style' => $style_name],
462 ])
463 ->save();
464
465 // Create a new node with an image attached.
466 $test_image = current($this->drupalGetTestFiles('image'));
467 $nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
468 $node = Node::load($nid);
469
470 // Get node field original image URI.
471 $fid = $node->get($field_name)->target_id;
472 $original_uri = File::load($fid)->getFileUri();
473
474 // Test that image is displayed using newly created style.
475 $this->drupalGet('node/' . $nid);
476 $this->assertRaw(file_url_transform_relative($style->buildUrl($original_uri)), format_string('Image displayed using style @style.', ['@style' => $style_name]));
477
478 // Copy config to sync, and delete the image style.
479 $sync = $this->container->get('config.storage.sync');
480 $active = $this->container->get('config.storage');
481 // Remove the image field from the display, to avoid a dependency error
482 // during import.
483 EntityViewDisplay::load('node.article.default')
484 ->removeComponent($field_name)
485 ->save();
486 $this->copyConfig($active, $sync);
487 $sync->delete('image.style.' . $style_name);
488 $this->configImporter()->import();
489
490 $this->assertFalse(ImageStyle::load($style_name), 'Style deleted after config import.');
491 $this->assertEqual($this->getImageCount($style), 0, 'Image style was flushed after being deleted by config import.');
492 }
493
494 /**
495 * Tests access for the image style listing.
496 */
497 public function testImageStyleAccess() {
498 $style = ImageStyle::create(['name' => 'style_foo', 'label' => $this->randomString()]);
499 $style->save();
500
501 $this->drupalGet('admin/config/media/image-styles');
502 $this->clickLink(t('Edit'));
503 $this->assertRaw(t('Select a new effect'));
504 }
505
506 }