first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
name: 'Image access test for hidden fields'
type: module
description: 'Provides an entity field access hook implementation to set an image field as hidden.'
package: Testing
# version: VERSION
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,21 @@
<?php
/**
* @file
* Image field access for hidden fields.
*/
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Access\AccessResult;
/**
* Implements hook_entity_field_access().
*/
function image_access_test_hidden_entity_field_access($operation, FieldDefinitionInterface $field_definition, AccountInterface $account, ?FieldItemListInterface $items = NULL) {
if ($field_definition->getName() == 'field_image' && $operation == 'edit') {
return AccessResult::forbidden();
}
return AccessResult::neutral();
}

View File

@@ -0,0 +1,10 @@
name: 'Image test'
type: module
description: 'Provides hook implementations for testing Image module functionality.'
package: Testing
# version: VERSION
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,48 @@
<?php
/**
* @file
* Provides Image module hook implementations for testing purposes.
*/
use Drupal\image\ImageStyleInterface;
function image_module_test_file_download($uri) {
$default_uri = \Drupal::state()->get('image.test_file_download', FALSE);
if ($default_uri == $uri) {
return ['X-Image-Owned-By' => 'image_module_test'];
}
}
/**
* Implements hook_image_effect_info_alter().
*/
function image_module_test_image_effect_info_alter(&$effects) {
$state = \Drupal::state();
// The 'image_module_test.counter' state variable value is set and accessed
// from the ImageEffectsTest::testImageEffectsCaching() test and used to
// signal if the image effect plugin definitions were computed or were
// retrieved from the cache.
// @see \Drupal\Tests\image\Kernel\ImageEffectsTest::testImageEffectsCaching()
$counter = $state->get('image_module_test.counter');
// Increase the test counter, signaling that image effects were processed,
// rather than being served from the cache.
$state->set('image_module_test.counter', ++$counter);
}
/**
* Implements hook_image_style_presave().
*
* Used to save test third party settings in the image style entity.
*/
function image_module_test_image_style_presave(ImageStyleInterface $style) {
$style->setThirdPartySetting('image_module_test', 'foo', 'bar');
}
/**
* Implements hook_image_style_flush().
*/
function image_module_test_image_style_flush($style, $path = NULL) {
$state = \Drupal::state();
$state->set('image_module_test_image_style_flush.called', $path);
}

View File

@@ -0,0 +1,39 @@
<?php
namespace Drupal\image_module_test\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Empty renderer for a dummy field with an AJAX handler.
*/
#[FieldFormatter(
id: 'image_module_test_dummy_ajax_formatter',
label: new TranslatableMarkup('Dummy AJAX'),
field_types: [
'image_module_test_dummy_ajax',
],
)]
class DummyAjaxFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->t('Renders nothing');
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
return $element;
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace Drupal\image_module_test\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Plugin implementation of the Dummy image formatter.
*/
#[FieldFormatter(
id: 'dummy_image_formatter',
label: new TranslatableMarkup('Dummy image'),
field_types: [
'image',
],
)]
class DummyImageFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
return [
['#markup' => 'Dummy'],
];
}
}

View File

@@ -0,0 +1,54 @@
<?php
namespace Drupal\image_module_test\Plugin\Field\FieldType;
use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
/**
* Defines a dummy field containing an AJAX handler.
*/
#[FieldType(
id: "image_module_test_dummy_ajax",
label: new TranslatableMarkup("Dummy AJAX"),
description: new TranslatableMarkup("A field containing an AJAX handler."),
default_widget: "image_module_test_dummy_ajax_widget",
default_formatter: "image_module_test_dummy_ajax_formatter"
)]
class DummyAjaxItem extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar',
'length' => 255,
],
],
];
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
return empty($this->get('value')->getValue());
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Dummy string value'));
return $properties;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Drupal\image_module_test\Plugin\Field\FieldWidget;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
/**
* Default widget for Dummy AJAX test.
*/
#[FieldWidget(
id: 'image_module_test_dummy_ajax_widget',
label: new TranslatableMarkup('Dummy AJAX widget'),
field_types: ['image_module_test_dummy_ajax'],
multiple_values: TRUE,
)]
class DummyAjaxWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['select_widget'] = [
'#type' => 'select',
'#title' => $this->t('Dummy select'),
'#options' => ['pow' => 'Pow!', 'bam' => 'Bam!'],
'#required' => TRUE,
'#ajax' => [
'callback' => static::class . '::dummyAjaxCallback',
'effect' => 'fade',
],
];
return $element;
}
/**
* Ajax callback for Dummy AJAX test.
*
* @param array $form
* The build form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* Ajax response.
*/
public static function dummyAjaxCallback(array &$form, FormStateInterface $form_state) {
return new AjaxResponse();
}
}

View File

@@ -0,0 +1,85 @@
<?php
namespace Drupal\image_module_test\Plugin\ImageEffect;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Image\ImageInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\image\Attribute\ImageEffect;
use Drupal\image\ConfigurableImageEffectBase;
/**
* Provides a test effect using Ajax in the configuration form.
*/
#[ImageEffect(
id: "image_module_test_ajax",
label: new TranslatableMarkup("Ajax test")
)]
class AjaxTestImageEffect extends ConfigurableImageEffectBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'test_parameter' => 0,
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['test_parameter'] = [
'#type' => 'number',
'#title' => $this->t('Test parameter'),
'#default_value' => $this->configuration['test_parameter'],
'#min' => 0,
];
$form['ajax_refresh'] = [
'#type' => 'button',
'#value' => $this->t('Ajax refresh'),
'#ajax' => ['callback' => [$this, 'ajaxCallback']],
];
$form['ajax_value'] = [
'#id' => 'ajax-value',
'#type' => 'item',
'#title' => $this->t('Ajax value'),
'#markup' => 'bar',
];
return $form;
}
/**
* AJAX callback.
*/
public function ajaxCallback($form, FormStateInterface $form_state) {
$item = [
'#type' => 'item',
'#title' => $this->t('Ajax value'),
'#markup' => microtime(),
];
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand('#ajax-value', $item));
return $response;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$this->configuration['test_parameter'] = $form_state->getValue('test_parameter');
}
/**
* {@inheritdoc}
*/
public function applyEffect(ImageInterface $image) {
return TRUE;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Drupal\image_module_test\Plugin\ImageEffect;
use Drupal\Core\Image\ImageInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\image\Attribute\ImageEffect;
use Drupal\image\ImageEffectBase;
/**
* Performs no operation on an image resource.
*/
#[ImageEffect(
id: "image_module_test_null",
label: new TranslatableMarkup("Image module test")
)]
class NullTestImageEffect extends ImageEffectBase {
/**
* {@inheritdoc}
*/
public function transformDimensions(array &$dimensions, $uri) {
// Unset image dimensions.
$dimensions['width'] = $dimensions['height'] = NULL;
}
/**
* {@inheritdoc}
*/
public function applyEffect(ImageInterface $image) {
return TRUE;
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Drupal\image_module_test\Plugin\ImageEffect;
use Drupal\Core\Image\ImageInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\image\Attribute\ImageEffect;
use Drupal\image\ImageEffectBase;
/**
* Performs an image operation that depends on the URI of the original image.
*/
#[ImageEffect(
id: "image_module_test_uri_dependent",
label: new TranslatableMarkup("URI dependent test image effect")
)]
class UriDependentTestImageEffect extends ImageEffectBase {
/**
* {@inheritdoc}
*/
public function transformDimensions(array &$dimensions, $uri) {
$dimensions = $this->getUriDependentDimensions($uri);
}
/**
* {@inheritdoc}
*/
public function applyEffect(ImageInterface $image) {
$dimensions = $this->getUriDependentDimensions($image->getSource());
return $image->resize($dimensions['width'], $dimensions['height']);
}
/**
* Make the image dimensions dependent on the image file extension.
*
* @param string $uri
* Original image file URI.
*
* @return array
* Associative array.
* - width: Integer with the derivative image width.
* - height: Integer with the derivative image height.
*/
protected function getUriDependentDimensions($uri) {
$dimensions = [];
$extension = pathinfo($uri, PATHINFO_EXTENSION);
switch (strtolower($extension)) {
case 'png':
$dimensions['width'] = $dimensions['height'] = 100;
break;
case 'gif':
$dimensions['width'] = $dimensions['height'] = 50;
break;
default:
$dimensions['width'] = $dimensions['height'] = 20;
break;
}
return $dimensions;
}
}

View File

@@ -0,0 +1,13 @@
name: 'Image test views'
type: module
description: 'Provides default views for views image tests.'
package: Testing
# version: VERSION
dependencies:
- drupal:image
- drupal:views
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,76 @@
langcode: en
status: true
dependencies:
module:
- file
- user
id: test_image_user_image_data
label: test_image_user_image_data
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
display:
default:
display_plugin: default
id: default
display_title: Default
position: 0
display_options:
access:
type: perm
options:
perm: 'access user profiles'
cache:
type: tag
style:
type: table
options:
grouping: { }
row_class: ''
default_row_class: true
override: true
sticky: false
caption: ''
summary: ''
description: ''
columns:
name: name
fid: fid
info:
name:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
fid:
sortable: false
default_sort_order: asc
align: ''
separator: ''
empty_column: false
responsive: ''
default: '-1'
empty_table: false
row:
type: fields
options:
inline: { }
separator: ''
hide_empty: false
default_field_elements: true
relationships:
user_picture_target_id:
id: user_picture_target_id
table: user__user_picture
field: user_picture_target_id
relationship: none
group_type: group
admin_label: 'image from user_picture'
required: true
plugin_id: standard
arguments: { }
display_extenders: { }

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for image.
*
* @group image
*/
class GenericTest extends GenericModuleTestBase {}

View File

@@ -0,0 +1,557 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\ImageStyleInterface;
use Drupal\node\Entity\Node;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests creation, deletion, and editing of image styles and effects.
*
* @group image
* @group #slow
*/
class ImageAdminStylesTest extends ImageFieldTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Given an image style, generate an image.
*/
public function createSampleImage(ImageStyleInterface $style) {
static $file_path;
// First, we need to make sure we have an image in our testing
// file directory. Copy over an image on the first run.
if (!isset($file_path)) {
$files = $this->drupalGetTestFiles('image');
$file = reset($files);
$file_path = \Drupal::service('file_system')->copy($file->uri, 'public://');
}
return $style->buildUrl($file_path) ? $file_path : FALSE;
}
/**
* Count the number of images currently create for a style.
*/
public function getImageCount(ImageStyleInterface $style) {
$count = 0;
if (is_dir('public://styles/' . $style->id())) {
$count = count(\Drupal::service('file_system')->scanDirectory('public://styles/' . $style->id(), '/.*/'));
}
return $count;
}
/**
* Tests creating an image style with a numeric name.
*/
public function testNumericStyleName(): void {
$style_name = rand();
$style_label = $this->randomString();
$edit = [
'name' => $style_name,
'label' => $style_label,
];
$this->drupalGet('admin/config/media/image-styles/add');
$this->submitForm($edit, 'Create new style');
$this->assertSession()->statusMessageContains("Style {$style_label} was created.", 'status');
$options = image_style_options();
$this->assertArrayHasKey($style_name, $options);
}
/**
* General test to add a style, add/remove/edit effects to it, then delete it.
*/
public function testStyle(): void {
$admin_path = 'admin/config/media/image-styles';
// Setup a style to be created and effects to add to it.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomString();
$style_path = $admin_path . '/manage/' . $style_name;
$effect_edits = [
'image_resize' => [
'width' => 100,
'height' => 101,
],
'image_scale' => [
'width' => 110,
'height' => 111,
'upscale' => 1,
],
'image_scale_and_crop' => [
'width' => 120,
'height' => 121,
],
'image_crop' => [
'width' => 130,
'height' => 131,
'anchor' => 'left-top',
],
'image_desaturate' => [
// No options for desaturate.
],
'image_rotate' => [
'degrees' => 5,
'random' => 1,
'bgcolor' => '#FFFF00',
],
];
// Add style form.
$edit = [
'name' => $style_name,
'label' => $style_label,
];
$this->drupalGet($admin_path . '/add');
$this->submitForm($edit, 'Create new style');
$this->assertSession()->statusMessageContains("Style {$style_label} was created.", 'status');
// Ensure that the expected entity operations are there.
$this->drupalGet($admin_path);
$this->assertSession()->linkByHrefExists($style_path);
$this->assertSession()->linkByHrefExists($style_path . '/flush');
$this->assertSession()->linkByHrefExists($style_path . '/delete');
// Add effect form.
// Add each sample effect to the style.
foreach ($effect_edits as $effect => $edit) {
$edit_data = [];
foreach ($edit as $field => $value) {
$edit_data['data[' . $field . ']'] = $value;
}
// Add the effect.
$this->drupalGet($style_path);
$this->submitForm(['new' => $effect], 'Add');
if (!empty($edit)) {
$effect_label = \Drupal::service('plugin.manager.image.effect')->createInstance($effect)->label();
$this->assertSession()->pageTextContains("Add {$effect_label} effect to style {$style_label}");
$this->submitForm($edit_data, 'Add effect');
}
}
// Load the saved image style.
$style = ImageStyle::load($style_name);
// Ensure that third party settings were added to the config entity.
// These are added by a hook_image_style_presave() implemented in
// image_module_test module.
$this->assertEquals('bar', $style->getThirdPartySetting('image_module_test', 'foo'), 'Third party settings were added to the image style.');
// Ensure that the image style URI matches our expected path.
$style_uri_path = $style->toUrl()->toString();
$this->assertStringContainsString($style_path, $style_uri_path, 'The image style URI is correct.');
// Confirm that all effects on the image style have settings that match
// what was saved.
$uuids = [];
foreach ($style->getEffects() as $uuid => $effect) {
// Store the uuid for later use.
$uuids[$effect->getPluginId()] = $uuid;
$effect_configuration = $effect->getConfiguration();
foreach ($effect_edits[$effect->getPluginId()] as $field => $value) {
$this->assertEquals($effect_configuration['data'][$field], $value, "The $field field in the {$effect->getPluginId()} effect has the correct value of $value.");
}
}
// Assert that every effect was saved.
foreach (array_keys($effect_edits) as $effect_name) {
$this->assertTrue(isset($uuids[$effect_name]), "A $effect_name effect was saved with ID $uuids[$effect_name]");
}
// Image style overview form (ordering and renaming).
// Confirm the order of effects is maintained according to the order we
// added the fields.
$effect_edits_order = array_keys($effect_edits);
$order_correct = TRUE;
$index = 0;
foreach ($style->getEffects() as $effect) {
if ($effect_edits_order[$index] != $effect->getPluginId()) {
$order_correct = FALSE;
}
$index++;
}
$this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
// Test the style overview form.
// Change the name of the style and adjust the weights of effects.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomMachineName();
$weight = count($effect_edits);
$edit = [
'name' => $style_name,
'label' => $style_label,
];
foreach ($style->getEffects() as $uuid => $effect) {
$edit['effects[' . $uuid . '][weight]'] = $weight;
$weight--;
}
// Create an image to make sure it gets flushed after saving.
$image_path = $this->createSampleImage($style);
$this->assertEquals(1, $this->getImageCount($style), "Image style {$style->label()} image $image_path successfully generated.");
$this->drupalGet($style_path);
$this->submitForm($edit, 'Save');
// Note that after changing the style name, the style path is changed.
$style_path = 'admin/config/media/image-styles/manage/' . $style_name;
// Check that the URL was updated.
$this->drupalGet($style_path);
$this->assertSession()->titleEquals("Edit style $style_label | Drupal");
// Check that the available image effects are properly sorted.
$option = $this->assertSession()->selectExists('edit-new--2')->findAll('css', 'option');
$this->assertEquals('Ajax test', $option[1]->getText(), '"Ajax test" is the first selectable effect.');
// Check that the image was flushed after updating the style.
// This is especially important when renaming the style. Make sure that
// the old image directory has been deleted.
$this->assertEquals(0, $this->getImageCount($style), "Image style {$style->label()} was flushed after renaming the style and updating the order of effects.");
// Load the style by the new name with the new weights.
$style = ImageStyle::load($style_name);
// Confirm the new style order was saved.
$effect_edits_order = array_reverse($effect_edits_order);
$order_correct = TRUE;
$index = 0;
foreach ($style->getEffects() as $effect) {
if ($effect_edits_order[$index] != $effect->getPluginId()) {
$order_correct = FALSE;
}
$index++;
}
$this->assertTrue($order_correct, 'The order of the effects is correctly set by default.');
// Image effect deletion form.
// Create an image to make sure it gets flushed after deleting an effect.
$image_path = $this->createSampleImage($style);
$this->assertEquals(1, $this->getImageCount($style), "Image style {$style->label()} image $image_path successfully generated.");
// Delete the 'image_crop' effect from the style.
$this->drupalGet($style_path . '/effects/' . $uuids['image_crop'] . '/delete');
$this->submitForm([], 'Delete');
// Confirm that the form submission was successful.
$this->assertSession()->statusCodeEquals(200);
$image_crop_effect = $style->getEffect($uuids['image_crop']);
$this->assertSession()->statusMessageContains("The image effect {$image_crop_effect->label()} has been deleted.", 'status');
// Confirm that there is no longer a link to the effect.
$this->assertSession()->linkByHrefNotExists($style_path . '/effects/' . $uuids['image_crop'] . '/delete');
// Refresh the image style information and verify that the effect was
// actually deleted.
$entity_type_manager = $this->container->get('entity_type.manager');
$style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style->id());
$this->assertFalse($style->getEffects()->has($uuids['image_crop']), "Effect with ID {$uuids['image_crop']} no longer found on image style {$style->label()}");
// Additional test on Rotate effect, for transparent background.
$edit = [
'data[degrees]' => 5,
'data[random]' => 0,
'data[bgcolor]' => '',
];
$this->drupalGet($style_path);
$this->submitForm(['new' => 'image_rotate'], 'Add');
$this->submitForm($edit, 'Add effect');
$entity_type_manager = $this->container->get('entity_type.manager');
$style = $entity_type_manager->getStorage('image_style')->loadUnchanged($style_name);
$this->assertCount(6, $style->getEffects(), 'Rotate effect with transparent background was added.');
// Style deletion form.
// Delete the style.
$this->drupalGet($style_path . '/delete');
$this->submitForm([], 'Delete');
// Confirm the style directory has been removed.
$directory = 'public://styles/' . $style_name;
$this->assertDirectoryDoesNotExist($directory);
$this->assertNull(ImageStyle::load($style_name), "Image style {$style->label()} successfully deleted.");
// Test empty text when there are no image styles.
// Delete all image styles.
foreach (ImageStyle::loadMultiple() as $image_style) {
$image_style->delete();
}
// Confirm that the empty text is correct on the image styles page.
$this->drupalGet($admin_path);
$this->assertSession()->pageTextContains("There are currently no styles. Add a new one.");
$this->assertSession()->linkByHrefExists(Url::fromRoute('image.style_add')->toString());
}
/**
* Tests deleting a style and choosing a replacement style.
*/
public function testStyleReplacement(): void {
// Create a new style.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomString();
$style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
$style->save();
$style_path = 'admin/config/media/image-styles/manage/';
// Create an image field that uses the new style.
$field_name = $this->randomMachineName(10);
$this->createImageField($field_name, 'node', 'article');
\Drupal::service('entity_display.repository')
->getViewDisplay('node', 'article')
->setComponent($field_name, [
'type' => 'image',
'settings' => ['image_style' => $style_name],
])
->save();
// Create a new node with an image attached.
$test_image = current($this->drupalGetTestFiles('image'));
$nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
$node = Node::load($nid);
// Get node field original image URI.
$fid = $node->get($field_name)->target_id;
$original_uri = File::load($fid)->getFileUri();
// Test that image is displayed using newly created style.
/** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
$file_url_generator = \Drupal::service('file_url_generator');
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseContains($file_url_generator->transformRelative($style->buildUrl($original_uri)));
// Rename the style and make sure the image field is updated.
$new_style_name = $this->randomMachineName(10);
$new_style_label = $this->randomString();
$edit = [
'name' => $new_style_name,
'label' => $new_style_label,
];
$this->drupalGet($style_path . $style_name);
$this->submitForm($edit, 'Save');
$this->assertSession()->statusMessageContains('Changes to the style have been saved.', 'status');
$this->drupalGet('node/' . $nid);
// Reload the image style using the new name.
$style = ImageStyle::load($new_style_name);
$this->assertSession()->responseContains($file_url_generator->transformRelative($style->buildUrl($original_uri)));
// Delete the style and choose a replacement style.
$edit = [
'replacement' => 'thumbnail',
];
$this->drupalGet($style_path . $new_style_name . '/delete');
$this->submitForm($edit, 'Delete');
$this->assertSession()->statusMessageContains("The image style {$new_style_label} has been deleted.", 'status');
$replacement_style = ImageStyle::load('thumbnail');
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseContains($file_url_generator->transformRelative($replacement_style->buildUrl($original_uri)));
}
/**
* Verifies that editing an image effect does not cause it to be duplicated.
*/
public function testEditEffect(): void {
// Add a scale effect.
$style_name = 'test_style_effect_edit';
$this->drupalGet('admin/config/media/image-styles/add');
$this->submitForm(['label' => 'Test style effect edit', 'name' => $style_name], 'Create new style');
$this->submitForm(['new' => 'image_scale_and_crop'], 'Add');
$this->submitForm(['data[width]' => '300', 'data[height]' => '200'], 'Add effect');
$this->assertSession()->pageTextContains('Scale and crop 300×200');
// There should normally be only one edit link on this page initially.
$this->clickLink('Edit');
$this->assertSession()->pageTextContains("Edit Scale and crop effect on style Test style effect edit");
$this->submitForm(['data[width]' => '360', 'data[height]' => '240'], 'Update effect');
$this->assertSession()->pageTextContains('Scale and crop 360×240');
// Check that the previous effect is replaced.
$this->assertSession()->pageTextNotContains('Scale and crop 300×200');
// Add another scale effect.
$this->drupalGet('admin/config/media/image-styles/add');
$this->submitForm(['label' => 'Test style scale edit scale', 'name' => 'test_style_scale_edit_scale'], 'Create new style');
$this->submitForm(['new' => 'image_scale'], 'Add');
$this->submitForm(['data[width]' => '12', 'data[height]' => '19'], 'Add effect');
// Edit the scale effect that was just added.
$this->clickLink('Edit');
$this->assertSession()->pageTextContains("Edit Scale effect on style Test style scale edit scale");
$this->submitForm(['data[width]' => '24', 'data[height]' => '19'], 'Update effect');
// Add another scale effect and make sure both exist. Click through from
// the overview to make sure that it is possible to add new effect then.
$this->drupalGet('admin/config/media/image-styles');
$rows = $this->xpath('//table/tbody/tr');
$i = 0;
foreach ($rows as $row) {
if ($row->find('css', 'td')->getText() === 'Test style scale edit scale') {
$this->clickLink('Edit', $i);
break;
}
$i++;
}
$this->submitForm(['new' => 'image_scale'], 'Add');
$this->submitForm(['data[width]' => '12', 'data[height]' => '19'], 'Add effect');
$this->assertSession()->pageTextContains('Scale 24×19');
$this->assertSession()->pageTextContains('Scale 12×19');
// Try to edit a nonexistent effect.
$uuid = $this->container->get('uuid');
$this->drupalGet('admin/config/media/image-styles/manage/' . $style_name . '/effects/' . $uuid->generate());
$this->assertSession()->statusCodeEquals(404);
}
/**
* Tests flush user interface.
*/
public function testFlushUserInterface(): void {
$admin_path = 'admin/config/media/image-styles';
// Create a new style.
$style_name = $this->randomMachineName(10);
$style = ImageStyle::create(['name' => $style_name, 'label' => $this->randomString()]);
$style->save();
// Create an image to make sure it gets flushed.
$files = $this->drupalGetTestFiles('image');
$image_uri = $files[0]->uri;
$derivative_uri = $style->buildUri($image_uri);
$this->assertTrue($style->createDerivative($image_uri, $derivative_uri));
$this->assertEquals(1, $this->getImageCount($style));
// Go to image styles list page and check if the flush operation link
// exists.
$this->drupalGet($admin_path);
$flush_path = $admin_path . '/manage/' . $style_name . '/flush';
$this->assertSession()->linkByHrefExists($flush_path);
// Flush the image style derivatives using the user interface.
$this->drupalGet($flush_path);
$this->submitForm([], 'Flush');
// The derivative image file should have been deleted.
$this->assertEquals(0, $this->getImageCount($style));
}
/**
* Tests image style configuration import that does a delete.
*/
public function testConfigImport(): void {
// Create a new style.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomString();
$style = ImageStyle::create(['name' => $style_name, 'label' => $style_label]);
$style->save();
// Create an image field that uses the new style.
$field_name = $this->randomMachineName(10);
$this->createImageField($field_name, 'node', 'article');
\Drupal::service('entity_display.repository')
->getViewDisplay('node', 'article')
->setComponent($field_name, [
'type' => 'image',
'settings' => ['image_style' => $style_name],
])
->save();
// Create a new node with an image attached.
$test_image = current($this->drupalGetTestFiles('image'));
$nid = $this->uploadNodeImage($test_image, $field_name, 'article', $this->randomMachineName());
$node = Node::load($nid);
// Get node field original image URI.
$fid = $node->get($field_name)->target_id;
$original_uri = File::load($fid)->getFileUri();
// Test that image is displayed using newly created style.
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseContains(\Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri)));
// Copy config to sync, and delete the image style.
$sync = $this->container->get('config.storage.sync');
$active = $this->container->get('config.storage');
// Remove the image field from the display, to avoid a dependency error
// during import.
EntityViewDisplay::load('node.article.default')
->removeComponent($field_name)
->save();
$this->copyConfig($active, $sync);
$sync->delete('image.style.' . $style_name);
$this->configImporter()->import();
$this->assertNull(ImageStyle::load($style_name), 'Style deleted after config import.');
$this->assertEquals(0, $this->getImageCount($style), 'Image style was flushed after being deleted by config import.');
}
/**
* Tests access for the image style listing.
*/
public function testImageStyleAccess(): void {
$style = ImageStyle::create(['name' => 'style_foo', 'label' => $this->randomString()]);
$style->save();
$this->drupalGet('admin/config/media/image-styles');
$this->clickLink('Edit');
$this->assertSession()->pageTextContains("Select a new effect");
}
/**
* Tests the display of preview images using a private scheme.
*/
public function testPreviewImageShowInPrivateScheme(): void {
$this->config('system.file')->set('default_scheme', 'private')->save();
/** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
$file_url_generator = \Drupal::service('file_url_generator');
// Get the original preview image file in core config.
$original_path = $this->config('image.settings')->get('preview_image');
$style = ImageStyle::create(['name' => 'test_foo', 'label' => 'test foo']);
$style->save();
// Build the derivative preview image file with the Image Style.
// @see template_preprocess_image_style_preview()
$preview_file = $style->buildUri($original_path);
$style->createDerivative($original_path, $preview_file);
// Check if the derivative image exists.
$this->assertFileExists($preview_file);
// Generate itok token for the preview image.
$itok = $style->getPathToken('private://' . $original_path);
$url = $file_url_generator->generateAbsoluteString($preview_file);
$url .= '?itok=' . $itok;
// Check if the preview image with style is shown.
$this->drupalGet($url);
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->responseHeaderContains('Content-Type', 'image/png');
}
}

View File

@@ -0,0 +1,312 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\File\FileExists;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests that images have correct dimensions when styled.
*
* @group image
*/
class ImageDimensionsTest extends BrowserTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['image', 'image_module_test'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
protected $profile = 'testing';
/**
* Tests styled image dimensions cumulatively.
*/
public function testImageDimensions(): void {
$image_factory = $this->container->get('image.factory');
// Create a working copy of the file.
$files = $this->drupalGetTestFiles('image');
$file = reset($files);
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$original_uri = $file_system->copy($file->uri, 'public://', FileExists::Rename);
// Create a style.
/** @var \Drupal\image\ImageStyleInterface $style */
$style = ImageStyle::create(['name' => 'test', 'label' => 'Test']);
$style->save();
$generated_uri = 'public://styles/test/public/' . $file_system->basename($original_uri);
/** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
$file_url_generator = \Drupal::service('file_url_generator');
$url = $file_url_generator->transformRelative($style->buildUrl($original_uri));
$variables = [
'#theme' => 'image_style',
'#style_name' => 'test',
'#uri' => $original_uri,
'#width' => 40,
'#height' => 20,
];
// Verify that the original image matches the hard-coded values.
$image_file = $image_factory->get($original_uri);
$this->assertEquals($variables['#width'], $image_file->getWidth());
$this->assertEquals($variables['#height'], $image_file->getHeight());
// Scale an image that is wider than it is high.
$effect = [
'id' => 'image_scale',
'data' => [
'width' => 120,
'height' => 90,
'upscale' => TRUE,
],
'weight' => 0,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="120" height="60" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(120, $image_file->getWidth());
$this->assertEquals(60, $image_file->getHeight());
// Rotate 90 degrees anticlockwise.
$effect = [
'id' => 'image_rotate',
'data' => [
'degrees' => -90,
'random' => FALSE,
],
'weight' => 1,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="60" height="120" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(60, $image_file->getWidth());
$this->assertEquals(120, $image_file->getHeight());
// Scale an image that is higher than it is wide (rotated by previous effect).
$effect = [
'id' => 'image_scale',
'data' => [
'width' => 120,
'height' => 90,
'upscale' => TRUE,
],
'weight' => 2,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="45" height="90" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(45, $image_file->getWidth());
$this->assertEquals(90, $image_file->getHeight());
// Test upscale disabled.
$effect = [
'id' => 'image_scale',
'data' => [
'width' => 400,
'height' => 200,
'upscale' => FALSE,
],
'weight' => 3,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="45" height="90" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(45, $image_file->getWidth());
$this->assertEquals(90, $image_file->getHeight());
// Add a desaturate effect.
$effect = [
'id' => 'image_desaturate',
'data' => [],
'weight' => 4,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="45" height="90" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(45, $image_file->getWidth());
$this->assertEquals(90, $image_file->getHeight());
// Add a random rotate effect.
$effect = [
'id' => 'image_rotate',
'data' => [
'degrees' => 180,
'random' => TRUE,
],
'weight' => 5,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" alt="" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
// Add a crop effect.
$effect = [
'id' => 'image_crop',
'data' => [
'width' => 30,
'height' => 30,
'anchor' => 'center-center',
],
'weight' => 6,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" width="30" height="30" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(30, $image_file->getWidth());
$this->assertEquals(30, $image_file->getHeight());
// Rotate to a non-multiple of 90 degrees.
$effect = [
'id' => 'image_rotate',
'data' => [
'degrees' => 57,
'random' => FALSE,
],
'weight' => 7,
];
$effect_id = $style->addImageEffect($effect);
$style->save();
// @todo Uncomment this once
// https://www.drupal.org/project/drupal/issues/2670966 is resolved.
// $this->assertEquals('<img src="' . $url . '" width="41" height="41" alt="" class="image-style-test" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
// @todo Uncomment this once
// https://www.drupal.org/project/drupal/issues/2670966 is resolved.
// $this->assertEquals(41, $image_file->getWidth());
// $this->assertEquals(41, $image_file->getHeight());
$effect_plugin = $style->getEffect($effect_id);
$style->deleteImageEffect($effect_plugin);
// Ensure that an effect can unset dimensions.
$effect = [
'id' => 'image_module_test_null',
'data' => [],
'weight' => 8,
];
$style->addImageEffect($effect);
$style->save();
$this->assertEquals('<img src="' . $url . '" alt="" />', $this->getImageTag($variables));
// Test URI dependent image effect.
$style = ImageStyle::create(['name' => 'test_uri', 'label' => 'Test URI']);
$effect = [
'id' => 'image_module_test_uri_dependent',
'data' => [],
'weight' => 0,
];
$style->addImageEffect($effect);
$style->save();
$variables = [
'#theme' => 'image_style',
'#style_name' => 'test_uri',
'#uri' => $original_uri,
'#width' => 40,
'#height' => 20,
];
// PNG original image. Should be resized to 100x100.
$generated_uri = 'public://styles/test_uri/public/' . $file_system->basename($original_uri);
$url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));
$this->assertEquals('<img src="' . $url . '" width="100" height="100" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(100, $image_file->getWidth());
$this->assertEquals(100, $image_file->getHeight());
// GIF original image. Should be resized to 50x50.
$file = $files[1];
$original_uri = $file_system->copy($file->uri, 'public://', FileExists::Rename);
$generated_uri = 'public://styles/test_uri/public/' . $file_system->basename($original_uri);
$url = $file_url_generator->transformRelative($style->buildUrl($original_uri));
$variables['#uri'] = $original_uri;
$this->assertEquals('<img src="' . $url . '" width="50" height="50" alt="" loading="lazy" />', $this->getImageTag($variables));
$this->assertFileDoesNotExist($generated_uri);
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
$image_file = $image_factory->get($generated_uri);
$this->assertEquals(50, $image_file->getWidth());
$this->assertEquals(50, $image_file->getHeight());
}
/**
* Render an image style element.
*
* Function \Drupal\Core\Render\RendererInterface::render() alters the passed
* $variables array by adding a new key '#printed' => TRUE. This prevents next
* call to re-render the element. We wrap
* \Drupal\Core\Render\RendererInterface::render() in a helper protected
* method and pass each time a fresh array so that $variables won't get
* altered and the element is re-rendered each time.
*/
protected function getImageTag($variables) {
return str_replace("\n", '', (string) \Drupal::service('renderer')->renderRoot($variables));
}
}

View File

@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\ImageEffect;
use Drupal\Core\File\FileExists;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\BrowserTestBase;
/**
* Tests for the Convert image effect.
*
* @group image
*/
class ConvertTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $modules = ['image'];
/**
* Tests that files stored in the root folder are converted properly.
*/
public function testConvertFileInRoot(): void {
// Create the test image style with a Convert effect.
$image_style = ImageStyle::create([
'name' => 'image_effect_test',
'label' => 'Image Effect Test',
]);
$this->assertEquals(SAVED_NEW, $image_style->save());
$image_style->addImageEffect([
'id' => 'image_convert',
'data' => [
'extension' => 'jpeg',
],
]);
$this->assertEquals(SAVED_UPDATED, $image_style->save());
// Create a copy of a test image file in root.
$test_uri = 'public://image-test-do.png';
\Drupal::service('file_system')->copy('core/tests/fixtures/files/image-test.png', $test_uri, FileExists::Replace);
$this->assertFileExists($test_uri);
// Execute the image style on the test image via a GET request.
$derivative_uri = 'public://styles/image_effect_test/public/image-test-do.png.jpeg';
$this->assertFileDoesNotExist($derivative_uri);
$url = \Drupal::service('file_url_generator')->transformRelative($image_style->buildUrl($test_uri));
$this->drupalGet($this->getAbsoluteUrl($url));
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($derivative_uri);
}
}

View File

@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\File\FileExists;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\Tests\EntityViewTrait;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests setting up default images both to the field and field storage.
*
* @group image
*/
class ImageFieldDefaultImagesTest extends ImageFieldTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
use EntityViewTrait {
buildEntityView as drupalBuildEntityView;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['field_ui'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests CRUD for fields and field storages with default images.
*/
public function testDefaultImages(): void {
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
// Create files to use as the default images.
$files = $this->drupalGetTestFiles('image');
// Create 10 files so the default image fids are not a single value.
for ($i = 1; $i <= 10; $i++) {
$filename = $this->randomMachineName() . "$i";
$desired_filepath = 'public://' . $filename;
\Drupal::service('file_system')->copy($files[0]->uri, $desired_filepath, FileExists::Error);
$file = File::create(['uri' => $desired_filepath, 'filename' => $filename, 'name' => $filename]);
$file->save();
}
$default_images = [];
foreach (['field_storage', 'field', 'field2', 'field_storage_new', 'field_new', 'field_storage_private', 'field_private'] as $image_target) {
$file = File::create((array) array_pop($files));
$file->save();
$default_images[$image_target] = $file;
}
// Create an image field storage and add a field to the article content
// type.
$field_name = $this->randomMachineName();
$storage_settings['default_image'] = [
'uuid' => $default_images['field_storage']->uuid(),
'alt' => '',
'title' => '',
'width' => 0,
'height' => 0,
];
$field_settings['default_image'] = [
'uuid' => $default_images['field']->uuid(),
'alt' => '',
'title' => '',
'width' => 0,
'height' => 0,
];
$widget_settings = [
'preview_image_style' => 'medium',
];
$field = $this->createImageField($field_name, 'node', 'article', $storage_settings, $field_settings, $widget_settings);
// The field default image id should be 2.
$this->assertEquals($default_images['field']->uuid(), $field->getSetting('default_image')['uuid']);
// Also test \Drupal\field\Entity\FieldConfig::getSettings().
$this->assertEquals($default_images['field']->uuid(), $field->getSettings()['default_image']['uuid']);
$field_storage = $field->getFieldStorageDefinition();
// The field storage default image id should be 1.
$this->assertEquals($default_images['field_storage']->uuid(), $field_storage->getSetting('default_image')['uuid']);
// Also test \Drupal\field\Entity\FieldStorageConfig::getSettings().
$this->assertEquals($default_images['field_storage']->uuid(), $field_storage->getSettings()['default_image']['uuid']);
// Add another field with another default image to the page content type.
$field2 = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'page',
'label' => $field->label(),
'required' => $field->isRequired(),
'settings' => [
'default_image' => [
'uuid' => $default_images['field2']->uuid(),
'alt' => '',
'title' => '',
'width' => 0,
'height' => 0,
],
],
]);
$field2->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$widget_settings = $display_repository->getFormDisplay('node', $field->getTargetBundle())->getComponent($field_name);
$display_repository->getFormDisplay('node', 'page')
->setComponent($field_name, $widget_settings)
->save();
$display_repository->getViewDisplay('node', 'page')
->setComponent($field_name)
->save();
// Confirm the defaults are present on the article field storage settings
// sub-form.
$field_id = $field->id();
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('field_storage[subform][settings][default_image][uuid][fids]', $default_images['field_storage']->id());
// Confirm the defaults are present on the article field edit form.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('settings[default_image][uuid][fids]', $default_images['field']->id());
// Confirm the defaults are present on the page field storage settings form.
$this->drupalGet("admin/structure/types/manage/page/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('field_storage[subform][settings][default_image][uuid][fids]', $default_images['field_storage']->id());
// Confirm the defaults are present on the page field edit form.
$field2_id = $field2->id();
$this->drupalGet("admin/structure/types/manage/page/fields/$field2_id");
$this->assertSession()->hiddenFieldValueEquals('settings[default_image][uuid][fids]', $default_images['field2']->id());
// Confirm that the image default is shown for a new article node.
$article = $this->drupalCreateNode(['type' => 'article']);
$article_built = $this->drupalBuildEntityView($article);
$this->assertEquals($default_images['field']->id(), $article_built[$field_name][0]['#item']->target_id, "A new article node without an image has the expected default image file ID of {$default_images['field']->id()}.");
// Also check that the field renders without warnings when the label is
// hidden.
EntityViewDisplay::load('node.article.default')
->setComponent($field_name, ['label' => 'hidden', 'type' => 'image'])
->save();
$this->drupalGet('node/' . $article->id());
// Confirm that the image default is shown for a new page node.
$page = $this->drupalCreateNode(['type' => 'page']);
$page_built = $this->drupalBuildEntityView($page);
$this->assertEquals($default_images['field2']->id(), $page_built[$field_name][0]['#item']->target_id, "A new page node without an image has the expected default image file ID of {$default_images['field2']->id()}.");
// Upload a new default for the field storage.
$default_image_settings = $field_storage->getSetting('default_image');
$default_image_settings['uuid'] = $default_images['field_storage_new']->uuid();
$field_storage->setSetting('default_image', $default_image_settings);
$field_storage->save();
// Confirm that the new default is used on the article field storage
// settings form.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('field_storage[subform][settings][default_image][uuid][fids]', $default_images['field_storage_new']->id());
// Reload the nodes and confirm the field defaults are used.
$node_storage->resetCache([$article->id(), $page->id()]);
$article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
$page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
$this->assertEquals($default_images['field']->id(), $article_built[$field_name][0]['#item']->target_id, "An existing article node without an image has the expected default image file ID of {$default_images['field']->id()}.");
$this->assertEquals($default_images['field2']->id(), $page_built[$field_name][0]['#item']->target_id, "An existing page node without an image has the expected default image file ID of {$default_images['field2']->id()}.");
// Upload a new default for the article's field.
$default_image_settings = $field->getSetting('default_image');
$default_image_settings['uuid'] = $default_images['field_new']->uuid();
$field->setSetting('default_image', $default_image_settings);
$field->save();
// Confirm the new field default is used on the article field admin form.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('settings[default_image][uuid][fids]', $default_images['field_new']->id());
// Reload the nodes.
$node_storage->resetCache([$article->id(), $page->id()]);
$article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
$page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
// Confirm the article uses the new default.
$this->assertEquals($default_images['field_new']->id(), $article_built[$field_name][0]['#item']->target_id, "An existing article node without an image has the expected default image file ID of {$default_images['field_new']->id()}.");
// Confirm the page remains unchanged.
$this->assertEquals($default_images['field2']->id(), $page_built[$field_name][0]['#item']->target_id, "An existing page node without an image has the expected default image file ID of {$default_images['field2']->id()}.");
// Confirm the default image is shown on the node form.
$file = File::load($default_images['field_new']->id());
$this->drupalGet('node/add/article');
$this->assertSession()->responseContains($file->getFilename());
// Remove the field default from articles.
$default_image_settings = $field->getSetting('default_image');
$default_image_settings['uuid'] = \Drupal::service('uuid')->generate();
$field->setSetting('default_image', $default_image_settings);
$field->save();
// Confirm the article field default has been removed.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('settings[default_image][uuid][fids]', '');
// Reload the nodes.
$node_storage->resetCache([$article->id(), $page->id()]);
$article_built = $this->drupalBuildEntityView($article = $node_storage->load($article->id()));
$page_built = $this->drupalBuildEntityView($page = $node_storage->load($page->id()));
// Confirm the article uses the new field storage (not field) default.
$this->assertEquals($default_images['field_storage_new']->id(), $article_built[$field_name][0]['#item']->target_id, "An existing article node without an image has the expected default image file ID of {$default_images['field_storage_new']->id()}.");
// Confirm the page remains unchanged.
$this->assertEquals($default_images['field2']->id(), $page_built[$field_name][0]['#item']->target_id, "An existing page node without an image has the expected default image file ID of {$default_images['field2']->id()}.");
$non_image = $this->drupalGetTestFiles('text');
$this->submitForm(['files[settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($non_image[0]->uri)], 'Upload');
$this->assertSession()->statusMessageContains('The specified file text-0.txt could not be uploaded.', 'error');
$this->assertSession()->statusMessageContains('Only files with the following extensions are allowed: png gif jpg jpeg webp.', 'error');
// Confirm the default image is shown on the node form.
$file = File::load($default_images['field_storage_new']->id());
$this->drupalGet('node/add/article');
$this->assertSession()->responseContains($file->getFilename());
// Change the default image for the field storage and also change the upload
// destination to the private filesystem at the same time.
$default_image_settings = $field_storage->getSetting('default_image');
$default_image_settings['uuid'] = $default_images['field_storage_private']->uuid();
$field_storage->setSetting('default_image', $default_image_settings);
$field_storage->setSetting('uri_scheme', 'private');
$field_storage->save();
// Confirm that the new default is used on the article field storage
// settings sub-form.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('field_storage[subform][settings][default_image][uuid][fids]', $default_images['field_storage_private']->id());
// Upload a new default for the article's field after setting the field
// storage upload destination to 'private'.
$default_image_settings = $field->getSetting('default_image');
$default_image_settings['uuid'] = $default_images['field_private']->uuid();
$field->setSetting('default_image', $default_image_settings);
$field->save();
// Confirm the new field default is used on the article field admin form.
$this->drupalGet("admin/structure/types/manage/article/fields/$field_id");
$this->assertSession()->hiddenFieldValueEquals('settings[default_image][uuid][fids]', $default_images['field_private']->id());
}
/**
* Tests image field and field storage having an invalid default image.
*/
public function testInvalidDefaultImage(): void {
$field_storage = FieldStorageConfig::create([
'field_name' => $this->randomMachineName(),
'entity_type' => 'node',
'type' => 'image',
'settings' => [
'default_image' => [
'uuid' => 100000,
],
],
]);
$field_storage->save();
$settings = $field_storage->getSettings();
// The non-existent default image should not be saved.
$this->assertNull($settings['default_image']['uuid']);
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'page',
'label' => $this->randomMachineName(),
'settings' => [
'default_image' => [
'uuid' => 100000,
],
],
]);
$field->save();
$settings = $field->getSettings();
// The non-existent default image should not be saved.
$this->assertNull($settings['default_image']['uuid']);
}
}

View File

@@ -0,0 +1,617 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\Core\Url;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
use Drupal\Tests\TestFileCreationTrait;
use Drupal\user\RoleInterface;
/**
* Tests the display of image fields.
*
* @group image
* @group #slow
*/
class ImageFieldDisplayTest extends ImageFieldTestBase {
use AssertPageCacheContextsAndTagsTrait;
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['field_ui'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests image formatters on node display for public files.
*/
public function testImageFieldFormattersPublic(): void {
$this->_testImageFieldFormatters('public');
}
/**
* Tests image formatters on node display for private files.
*/
public function testImageFieldFormattersPrivate(): void {
// Remove access content permission from anonymous users.
user_role_change_permissions(RoleInterface::ANONYMOUS_ID, ['access content' => FALSE]);
$this->_testImageFieldFormatters('private');
}
/**
* Tests image formatters on node display.
*/
public function _testImageFieldFormatters($scheme) {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
$field_name = $this->randomMachineName();
$field_settings = ['alt_field_required' => 0];
$instance = $this->createImageField($field_name, 'node', 'article', ['uri_scheme' => $scheme], $field_settings);
// Go to manage display page.
$this->drupalGet("admin/structure/types/manage/article/display");
// Test for existence of link to image styles configuration.
$this->submitForm([], "{$field_name}_settings_edit");
$this->assertSession()->linkByHrefExists(Url::fromRoute('entity.image_style.collection')->toString(), 0, 'Link to image styles configuration is found');
// Remove 'administer image styles' permission from testing admin user.
$admin_user_roles = $this->adminUser->getRoles(TRUE);
user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => FALSE]);
// Go to manage display page again.
$this->drupalGet("admin/structure/types/manage/article/display");
// Test for absence of link to image styles configuration.
$this->submitForm([], "{$field_name}_settings_edit");
$this->assertSession()->linkByHrefNotExists(Url::fromRoute('entity.image_style.collection')->toString(), 'Link to image styles configuration is absent when permissions are insufficient');
// Restore 'administer image styles' permission to testing admin user
user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
// Create a new node with an image attached.
$test_image = current($this->drupalGetTestFiles('image'));
// Ensure that preview works.
$this->previewNodeImage($test_image, $field_name, 'article');
// After previewing, make the alt field required. It cannot be required
// during preview because the form validation will fail.
$instance->setSetting('alt_field_required', 1);
$instance->save();
// Create alt text for the image.
$alt = $this->randomMachineName();
// Save node.
$nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
// Test that the default formatter is being used.
/** @var \Drupal\file\FileInterface $file */
$file = $node->{$field_name}->entity;
$image_uri = $file->getFileUri();
$image = [
'#theme' => 'image',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#alt' => $alt,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->assertSession()->responseContains($default_output);
// Test the image linked to file formatter.
$display_options = [
'type' => 'image',
'settings' => ['image_link' => 'file'],
];
$display = \Drupal::service('entity_display.repository')
->getViewDisplay('node', $node->getType());
$display->setComponent($field_name, $display_options)
->save();
$image = [
'#theme' => 'image',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#alt' => $alt,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = '<a href="' . $file->createFileUrl() . '">' . (string) $renderer->renderRoot($image) . '</a>';
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
// @todo Remove in https://www.drupal.org/node/2646744.
$this->assertCacheContext('url.site');
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
$this->assertSession()->responseContains($default_output);
// Verify that the image can be downloaded.
$this->assertEquals(file_get_contents($test_image->uri), $this->drupalGet($file->createFileUrl(FALSE)), 'File was downloaded successfully.');
if ($scheme == 'private') {
// Only verify HTTP headers when using private scheme and the headers are
// sent by Drupal.
$this->assertSession()->responseHeaderEquals('Content-Type', 'image/png');
$this->assertSession()->responseHeaderContains('Cache-Control', 'private');
// Log out and ensure the file cannot be accessed.
$this->drupalLogout();
$this->drupalGet($file->createFileUrl(FALSE));
$this->assertSession()->statusCodeEquals(403);
// Log in again.
$this->drupalLogin($this->adminUser);
}
// Test the image linked to content formatter.
$display_options['settings']['image_link'] = 'content';
$display->setComponent($field_name, $display_options)
->save();
$image = [
'#theme' => 'image',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
];
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
$this->assertSession()->elementsCount('xpath', '//a[@href="' . $node->toUrl()->toString() . '"]/img[@src="' . $file->createFileUrl() . '" and @alt="' . $alt . '" and @width="' . $image['#width'] . '" and @height="' . $image['#height'] . '"]', 1);
// Test the image style 'thumbnail' formatter.
$display_options['settings']['image_link'] = '';
$display_options['settings']['image_style'] = 'thumbnail';
$display->setComponent($field_name, $display_options)
->save();
// Ensure the derivative image is generated so we do not have to deal with
// image style callback paths.
$this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
$image_style = [
'#theme' => 'image_style',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#style_name' => 'thumbnail',
'#alt' => $alt,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = (string) $renderer->renderRoot($image_style);
$this->drupalGet('node/' . $nid);
$image_style = ImageStyle::load('thumbnail');
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $image_style->getCacheTags()[0]);
$this->assertSession()->responseContains($default_output);
if ($scheme == 'private') {
// Log out and ensure the file cannot be accessed.
$this->drupalLogout();
$this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
$this->assertSession()->statusCodeEquals(403);
// Log in again.
$this->drupalLogin($this->adminUser);
}
// Test the image URL formatter without an image style.
$display_options = [
'type' => 'image_url',
'settings' => ['image_style' => ''],
];
$expected_url = $file->createFileUrl();
$this->assertEquals($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
// Test the image URL formatter with an image style.
$display_options['settings']['image_style'] = 'thumbnail';
$expected_url = \Drupal::service('file_url_generator')->transformRelative(ImageStyle::load('thumbnail')->buildUrl($image_uri));
$this->assertEquals($expected_url, $node->{$field_name}->view($display_options)[0]['#markup']);
// Test the settings summary.
$display_options = [
'type' => 'image_url',
'settings' => [
'image_style' => 'thumbnail',
],
];
$display = \Drupal::service('entity_display.repository')->getViewDisplay('node', $node->getType(), 'default');
$display->setComponent($field_name, $display_options)->save();
$this->drupalGet("admin/structure/types/manage/" . $node->getType() . "/display");
$this->assertSession()->responseContains('Image style: Thumbnail (100×100)');
}
/**
* Tests for image field settings.
*/
public function testImageFieldSettings(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
$test_image = current($this->drupalGetTestFiles('image'));
[, $test_image_extension] = explode('.', $test_image->filename);
$field_name = $this->randomMachineName();
$field_settings = [
'alt_field' => 1,
'file_extensions' => $test_image_extension,
'max_filesize' => '50 KB',
'max_resolution' => '100x100',
'min_resolution' => '10x10',
'title_field' => 1,
];
$widget_settings = [
'preview_image_style' => 'medium',
];
$field = $this->createImageField($field_name, 'node', 'article', [], $field_settings, $widget_settings);
// Verify that the min/max dimensions set on the field are properly
// extracted, and displayed, on the image field's configuration form.
$this->drupalGet('admin/structure/types/manage/article/fields/' . $field->id());
$this->assertSession()->fieldValueEquals('settings[max_resolution][x]', '100');
$this->assertSession()->fieldValueEquals('settings[max_resolution][y]', '100');
$this->assertSession()->fieldValueEquals('settings[min_resolution][x]', '10');
$this->assertSession()->fieldValueEquals('settings[min_resolution][y]', '10');
$this->drupalGet('node/add/article');
$this->assertSession()->pageTextContains('50 KB limit.');
$this->assertSession()->pageTextContains('Allowed types: ' . $test_image_extension . '.');
$this->assertSession()->pageTextContains('Images must be larger than 10x10 pixels. Images larger than 100x100 pixels will be resized.');
// We have to create the article first and then edit it because the alt
// and title fields do not display until the image has been attached.
// Create alt text for the image.
$alt = $this->randomMachineName();
$nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
$this->drupalGet('node/' . $nid . '/edit');
// Verify that the optional fields alt & title are saved & filled.
$this->assertSession()->fieldValueEquals($field_name . '[0][alt]', $alt);
$this->assertSession()->fieldValueEquals($field_name . '[0][title]', '');
// Verify that the attached image is being previewed using the 'medium'
// style.
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
$file = $node->{$field_name}->entity;
$file_url_generator = \Drupal::service('file_url_generator');
$url = $file_url_generator->transformRelative(ImageStyle::load('medium')->buildUrl($file->getFileUri()));
$this->assertSession()->elementExists('css', 'img[width=40][height=20][src="' . $url . '"]');
// Add alt/title fields to the image and verify that they are displayed.
$image = [
'#theme' => 'image',
'#uri' => $file->getFileUri(),
'#alt' => $alt,
'#title' => $this->randomMachineName(),
'#width' => 40,
'#height' => 20,
'#attributes' => ['loading' => 'lazy'],
];
$edit = [
$field_name . '[0][alt]' => $image['#alt'],
$field_name . '[0][title]' => $image['#title'],
];
$this->drupalGet('node/' . $nid . '/edit');
$this->submitForm($edit, 'Save');
$default_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->assertSession()->responseContains($default_output);
// Verify that alt/title longer than allowed results in a validation error.
$test_size = 2000;
$edit = [
$field_name . '[0][alt]' => $this->randomMachineName($test_size),
$field_name . '[0][title]' => $this->randomMachineName($test_size),
];
$this->drupalGet('node/' . $nid . '/edit');
$this->submitForm($edit, 'Save');
$schema = $field->getFieldStorageDefinition()->getSchema();
$this->assertSession()->statusMessageContains("Alternative text cannot be longer than {$schema['columns']['alt']['length']} characters but is currently {$test_size} characters long.", 'error');
$this->assertSession()->statusMessageContains("Title cannot be longer than {$schema['columns']['title']['length']} characters but is currently {$test_size} characters long.", 'error');
// Set cardinality to unlimited and add upload a second image.
// The image widget is extending on the file widget, but the image field
// type does not have the 'display_field' setting which is expected by
// the file widget. This resulted in notices before when cardinality is not
// 1, so we need to make sure the file widget prevents these notices by
// providing all settings, even if they are not used.
// @see FileWidget::formMultipleElements().
$this->drupalGet('admin/structure/types/manage/article/fields/node.article.' . $field_name);
$this->submitForm([
'field_storage[subform][cardinality]' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
], 'Save');
$edit = [
'files[' . $field_name . '_1][]' => \Drupal::service('file_system')->realpath($test_image->uri),
];
$this->drupalGet('node/' . $node->id() . '/edit');
$this->submitForm($edit, 'Save');
// Add the required alt text.
$this->submitForm([$field_name . '[1][alt]' => $alt], 'Save');
$this->assertSession()->statusMessageContains('Article ' . $node->getTitle() . ' has been updated.', 'status');
// Assert ImageWidget::process() calls FieldWidget::process().
$this->drupalGet('node/' . $node->id() . '/edit');
$edit = [
'files[' . $field_name . '_2][]' => \Drupal::service('file_system')->realpath($test_image->uri),
];
$this->submitForm($edit, $field_name . '_2_upload_button');
$this->assertSession()->elementNotExists('css', 'input[name="files[' . $field_name . '_2][]"]');
$this->assertSession()->elementExists('css', 'input[name="files[' . $field_name . '_3][]"]');
}
/**
* Tests for image loading attribute settings.
*/
public function testImageLoadingAttribute(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
$field_name = $this->randomMachineName();
$field_settings = ['alt_field_required' => 0];
$instance = $this->createImageField($field_name, 'node', 'article', [], $field_settings);
// Go to manage display page.
$this->drupalGet("admin/structure/types/manage/article/display");
// Test for existence of link to image styles configuration.
$this->submitForm([], "{$field_name}_settings_edit");
$this->assertSession()->linkByHrefExists(Url::fromRoute('entity.image_style.collection')->toString(), 0, 'Link to image styles configuration is found');
// Remove 'administer image styles' permission from testing admin user.
$admin_user_roles = $this->adminUser->getRoles(TRUE);
user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => FALSE]);
// Go to manage display page again.
$this->drupalGet("admin/structure/types/manage/article/display");
// Test for absence of link to image styles configuration.
$this->submitForm([], "{$field_name}_settings_edit");
$this->assertSession()->linkByHrefNotExists(Url::fromRoute('entity.image_style.collection')->toString(), 'Link to image styles configuration is absent when permissions are insufficient');
// Restore 'administer image styles' permission to testing admin user
user_role_change_permissions(reset($admin_user_roles), ['administer image styles' => TRUE]);
// Create a new node with an image attached.
$test_image = current($this->drupalGetTestFiles('image'));
// Ensure that preview works.
$this->previewNodeImage($test_image, $field_name, 'article');
// After previewing, make the alt field required. It cannot be required
// during preview because the form validation will fail.
$instance->setSetting('alt_field_required', 1);
$instance->save();
// Create alt text for the image.
$alt = $this->randomMachineName();
// Save node.
$nid = $this->uploadNodeImage($test_image, $field_name, 'article', $alt);
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
// Test that the default image loading attribute is being used.
/** @var \Drupal\file\FileInterface $file */
$file = $node->{$field_name}->entity;
$image_uri = $file->getFileUri();
$image = [
'#theme' => 'image',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#alt' => $alt,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->assertSession()->responseContains($default_output);
// Test overrides of image loading attribute.
$display_options = [
'type' => 'image',
'settings' => [
'image_link' => '',
'image_style' => '',
'image_loading' => ['attribute' => 'eager'],
],
];
$display = \Drupal::service('entity_display.repository')
->getViewDisplay('node', $node->getType());
$display->setComponent($field_name, $display_options)
->save();
$image = [
'#theme' => 'image',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#alt' => $alt,
'#attributes' => ['loading' => 'eager'],
];
$default_output = (string) $renderer->renderRoot($image);
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseContains($default_output);
// Test the image loading "priority" formatter works together with "image_style".
$display_options['settings']['image_style'] = 'thumbnail';
$display->setComponent($field_name, $display_options)
->save();
// Ensure the derivative image is generated so we do not have to deal with
// image style callback paths.
$this->drupalGet(ImageStyle::load('thumbnail')->buildUrl($image_uri));
$image_style = [
'#theme' => 'image_style',
'#uri' => $image_uri,
'#width' => 40,
'#height' => 20,
'#style_name' => 'thumbnail',
'#alt' => $alt,
'#attributes' => ['loading' => 'eager'],
];
$default_output = (string) $renderer->renderRoot($image_style);
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseContains($default_output);
}
/**
* Tests use of a default image with an image field.
*/
public function testImageFieldDefaultImage(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$node_storage = $this->container->get('entity_type.manager')->getStorage('node');
// Create a new image field.
$field_name = $this->randomMachineName();
$this->createImageField($field_name, 'node', 'article');
// Create a new node, with no images and verify that no images are
// displayed.
$node = $this->drupalCreateNode(['type' => 'article']);
$this->drupalGet('node/' . $node->id());
// Verify that no image is displayed on the page by checking for the class
// that would be used on the image field.
$this->assertSession()->responseNotMatches('<div class="(.*?)field--name-' . strtr($field_name, '_', '-') . '(.*?)">');
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
// Add a default image to the public image field.
$images = $this->drupalGetTestFiles('image');
$alt = $this->randomString(512);
$title = $this->randomString(1024);
$edit = [
// Get the path of the 'image-test.png' file.
'files[field_storage_subform_settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($images[0]->uri),
'field_storage[subform][settings][default_image][alt]' => $alt,
'field_storage[subform][settings][default_image][title]' => $title,
];
$this->drupalGet("admin/structure/types/manage/article/fields/node.article.{$field_name}");
$this->submitForm($edit, 'Save');
// Clear field definition cache so the new default image is detected.
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
$field_storage = FieldStorageConfig::loadByName('node', $field_name);
$default_image = $field_storage->getSetting('default_image');
$file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
$this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
$image = [
'#theme' => 'image',
'#uri' => $file->getFileUri(),
'#alt' => $alt,
'#title' => $title,
'#width' => 40,
'#height' => 20,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->drupalGet('node/' . $node->id());
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
$this->assertSession()->responseContains($default_output);
// Create a node with an image attached and ensure that the default image
// is not displayed.
// Create alt text for the image.
$alt = $this->randomMachineName();
// Upload the 'image-test.gif' file.
$nid = $this->uploadNodeImage($images[2], $field_name, 'article', $alt);
$node_storage->resetCache([$nid]);
$node = $node_storage->load($nid);
$file = $node->{$field_name}->entity;
$image = [
'#theme' => 'image',
'#uri' => $file->getFileUri(),
'#width' => 40,
'#height' => 20,
'#alt' => $alt,
'#attributes' => ['loading' => 'lazy'],
];
$image_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->drupalGet('node/' . $nid);
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
// Default image should not be displayed.
$this->assertSession()->responseNotContains($default_output);
// User supplied image should be displayed.
$this->assertSession()->responseContains($image_output);
// Remove default image from the field and make sure it is no longer used.
// Can't use fillField cause Mink can't fill hidden fields.
$this->drupalGet("admin/structure/types/manage/article/fields/node.article.$field_name");
$this->getSession()->getPage()->find('css', 'input[name="field_storage[subform][settings][default_image][uuid][fids]"]')->setValue(0);
$this->getSession()->getPage()->pressButton('Save');
// Clear field definition cache so the new default image is detected.
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
$field_storage = FieldStorageConfig::loadByName('node', $field_name);
$default_image = $field_storage->getSetting('default_image');
$this->assertEmpty($default_image['uuid'], 'Default image removed from field.');
// Create an image field that uses the private:// scheme and test that the
// default image works as expected.
$private_field_name = $this->randomMachineName();
$this->createImageField($private_field_name, 'node', 'article', ['uri_scheme' => 'private']);
// Add a default image to the new field.
$edit = [
// Get the path of the 'image-test.gif' file.
'files[field_storage_subform_settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($images[2]->uri),
'field_storage[subform][settings][default_image][alt]' => $alt,
'field_storage[subform][settings][default_image][title]' => $title,
];
$this->drupalGet('admin/structure/types/manage/article/fields/node.article.' . $private_field_name);
$this->submitForm($edit, 'Save');
// Clear field definition cache so the new default image is detected.
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
$private_field_storage = FieldStorageConfig::loadByName('node', $private_field_name);
$default_image = $private_field_storage->getSetting('default_image');
$file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
$this->assertEquals('private', StreamWrapperManager::getScheme($file->getFileUri()), 'Default image uses private:// scheme.');
$this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
// Create a new node with no image attached and ensure that default private
// image is displayed.
$node = $this->drupalCreateNode(['type' => 'article']);
$image = [
'#theme' => 'image',
'#uri' => $file->getFileUri(),
'#alt' => $alt,
'#title' => $title,
'#width' => 40,
'#height' => 20,
'#attributes' => ['loading' => 'lazy'],
];
$default_output = str_replace("\n", '', (string) $renderer->renderRoot($image));
$this->drupalGet('node/' . $node->id());
$this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
// Verify that no image style cache tags are found.
$this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
// Default private image should be displayed when no user supplied image
// is present.
$this->assertSession()->responseContains($default_output);
}
}

View File

@@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\BrowserTestBase;
/**
* @todo Test the following functions.
*
* In file:
* - image.effects.inc:
* image_style_generate()
* \Drupal\image\ImageStyleInterface::createDerivative()
*
* - image.module:
* image_style_options()
* \Drupal\image\ImageStyleInterface::flush()
* image_filter_keyword()
*/
/**
* This class provides methods specifically for testing Image's field handling.
*/
abstract class ImageFieldTestBase extends BrowserTestBase {
use ImageFieldCreationTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'node',
'image',
'field_ui',
'image_module_test',
];
/**
* A user with permissions to administer content types and image styles.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create Basic page and Article node types.
if ($this->profile != 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
$this->adminUser = $this->drupalCreateUser([
'access content',
'access administration pages',
'administer site configuration',
'administer content types',
'administer node fields',
'administer nodes',
'create article content',
'edit any article content',
'delete any article content',
'administer image styles',
'administer node display',
]);
$this->drupalLogin($this->adminUser);
}
/**
* Preview an image in a node.
*
* @param \Drupal\Core\Image\ImageInterface $image
* A file object representing the image to upload.
* @param string $field_name
* Name of the image field the image should be attached to.
* @param string $type
* The type of node to create.
*/
public function previewNodeImage($image, $field_name, $type) {
$edit = [
'title[0][value]' => $this->randomMachineName(),
];
$edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')->realpath($image->uri);
$this->drupalGet('node/add/' . $type);
$this->submitForm($edit, 'Preview');
}
/**
* Upload an image to a node.
*
* @param $image
* A file object representing the image to upload.
* @param $field_name
* Name of the image field the image should be attached to.
* @param $type
* The type of node to create.
* @param $alt
* The alt text for the image. Use if the field settings require alt text.
*/
public function uploadNodeImage($image, $field_name, $type, $alt = '') {
$edit = [
'title[0][value]' => $this->randomMachineName(),
];
$edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system')->realpath($image->uri);
$this->drupalGet('node/add/' . $type);
$this->submitForm($edit, 'Save');
if ($alt) {
// Add alt text.
$this->submitForm([$field_name . '[0][alt]' => $alt], 'Save');
}
// Retrieve ID of the newly created node from the current URL.
$matches = [];
preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
return $matches[1] ?? FALSE;
}
/**
* Retrieves the fid of the last inserted file.
*/
protected function getLastFileId() {
return (int) \Drupal::entityQueryAggregate('file')
->accessCheck(FALSE)
->aggregate('fid', 'max')
->execute()[0]['fid_max'];
}
}

View File

@@ -0,0 +1,285 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests validation functions such as min/max dimensions.
*
* @group image
* @group #slow
*/
class ImageFieldValidateTest extends ImageFieldTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests image validity.
*/
public function testValid(): void {
$file_system = $this->container->get('file_system');
$image_files = $this->drupalGetTestFiles('image');
$field_name = $this->randomMachineName();
$this->createImageField($field_name, 'node', 'article', [], ['file_directory' => 'test-upload']);
$expected_path = 'public://test-upload';
// Create alt text for the image.
$alt = $this->randomMachineName();
// Create a node with a valid image.
$node = $this->uploadNodeImage($image_files[0], $field_name, 'article', $alt);
$this->assertFileExists($expected_path . '/' . $image_files[0]->filename);
// Remove the image.
$this->drupalGet('node/' . $node . '/edit');
$this->submitForm([], 'Remove');
$this->submitForm([], 'Save');
// Get invalid image test files.
$dir = 'core/tests/fixtures/files';
$files = [];
if (is_dir($dir)) {
$files = $file_system->scanDirectory($dir, '/invalid-img-.*/');
}
$invalid_image_files = [];
foreach ($files as $file) {
$invalid_image_files[$file->filename] = $file;
}
// Try uploading a zero-byte image.
$zero_size_image = $invalid_image_files['invalid-img-zero-size.png'];
$edit = [
'files[' . $field_name . '_0]' => $file_system->realpath($zero_size_image->uri),
];
$this->drupalGet('node/' . $node . '/edit');
$this->submitForm($edit, 'Upload');
$this->assertFileDoesNotExist($expected_path . '/' . $zero_size_image->filename);
// Try uploading an invalid image.
$invalid_image = $invalid_image_files['invalid-img-test.png'];
$edit = [
'files[' . $field_name . '_0]' => $file_system->realpath($invalid_image->uri),
];
$this->drupalGet('node/' . $node . '/edit');
$this->submitForm($edit, 'Upload');
$this->assertFileDoesNotExist($expected_path . '/' . $invalid_image->filename);
// Upload a valid image again.
$valid_image = $image_files[0];
$edit = [
'files[' . $field_name . '_0]' => $file_system->realpath($valid_image->uri),
];
$this->drupalGet('node/' . $node . '/edit');
$this->submitForm($edit, 'Upload');
$this->assertFileExists($expected_path . '/' . $valid_image->filename);
}
/**
* Tests min/max dimensions settings.
*/
public function testResolution(): void {
$field_names = [
0 => $this->randomMachineName(),
1 => $this->randomMachineName(),
2 => $this->randomMachineName(),
];
$min_resolution = [
'width' => 50,
'height' => 50,
];
$max_resolution = [
'width' => 100,
'height' => 100,
];
$no_height_min_resolution = [
'width' => 50,
'height' => NULL,
];
$no_height_max_resolution = [
'width' => 100,
'height' => NULL,
];
$no_width_min_resolution = [
'width' => NULL,
'height' => 50,
];
$no_width_max_resolution = [
'width' => NULL,
'height' => 100,
];
$field_settings = [
0 => $this->getFieldSettings($min_resolution, $max_resolution),
1 => $this->getFieldSettings($no_height_min_resolution, $no_height_max_resolution),
2 => $this->getFieldSettings($no_width_min_resolution, $no_width_max_resolution),
];
$this->createImageField($field_names[0], 'node', 'article', [], $field_settings[0]);
$this->createImageField($field_names[1], 'node', 'article', [], $field_settings[1]);
$this->createImageField($field_names[2], 'node', 'article', [], $field_settings[2]);
// We want a test image that is too small, and a test image that is too
// big, so cycle through test image files until we have what we need.
$image_that_is_too_big = FALSE;
$image_that_is_too_small = FALSE;
$image_factory = $this->container->get('image.factory');
foreach ($this->drupalGetTestFiles('image') as $image) {
$image_file = $image_factory->get($image->uri);
if ($image_file->getWidth() > $max_resolution['width']) {
$image_that_is_too_big = $image;
}
if ($image_file->getWidth() < $min_resolution['width']) {
$image_that_is_too_small = $image;
$image_that_is_too_small_file = $image_file;
}
if ($image_that_is_too_small && $image_that_is_too_big) {
break;
}
}
$this->uploadNodeImage($image_that_is_too_small, $field_names[0], 'article');
$this->assertSession()->statusMessageContains("The specified file {$image_that_is_too_small->filename} could not be uploaded.", 'error');
$this->assertSession()->statusMessageContains("The image is too small. The minimum dimensions are 50x50 pixels and the image size is {$image_that_is_too_small_file->getWidth()}x{$image_that_is_too_small_file->getHeight()} pixels.", 'error');
$this->uploadNodeImage($image_that_is_too_big, $field_names[0], 'article');
$this->assertSession()->statusMessageContains('The image was resized to fit within the maximum allowed dimensions of 100x100 pixels.', 'status');
$this->uploadNodeImage($image_that_is_too_small, $field_names[1], 'article');
$this->assertSession()->statusMessageContains("The specified file {$image_that_is_too_small->filename} could not be uploaded.", 'error');
$this->uploadNodeImage($image_that_is_too_big, $field_names[1], 'article');
$this->assertSession()->statusMessageContains('The image was resized to fit within the maximum allowed width of 100 pixels.', 'status');
$this->uploadNodeImage($image_that_is_too_small, $field_names[2], 'article');
$this->assertSession()->statusMessageContains("The specified file {$image_that_is_too_small->filename} could not be uploaded.", 'error');
$this->uploadNodeImage($image_that_is_too_big, $field_names[2], 'article');
$this->assertSession()->statusMessageContains('The image was resized to fit within the maximum allowed height of 100 pixels.', 'status');
}
/**
* Tests that required alt/title fields gets validated right.
*/
public function testRequiredAttributes(): void {
$field_name = $this->randomMachineName();
$field_settings = [
'alt_field' => 1,
'alt_field_required' => 1,
'title_field' => 1,
'title_field_required' => 1,
'required' => 1,
];
$instance = $this->createImageField($field_name, 'node', 'article', [], $field_settings);
$images = $this->drupalGetTestFiles('image');
// Let's just use the first image.
$image = $images[0];
$this->uploadNodeImage($image, $field_name, 'article');
// Look for form-required for the alt text.
$this->assertSession()->elementExists('xpath', '//label[@for="edit-' . $field_name . '-0-alt" and @class="js-form-required form-required"]/following-sibling::input[@id="edit-' . $field_name . '-0-alt"]');
$this->assertSession()->elementExists('xpath', '//label[@for="edit-' . $field_name . '-0-title" and @class="js-form-required form-required"]/following-sibling::input[@id="edit-' . $field_name . '-0-title"]');
$this->assertSession()->statusMessageContains('Alternative text field is required.', 'error');
$this->assertSession()->statusMessageContains('Title field is required.', 'error');
$instance->setSetting('alt_field_required', 0);
$instance->setSetting('title_field_required', 0);
$instance->save();
$edit = [
'title[0][value]' => $this->randomMachineName(),
];
$this->drupalGet('node/add/article');
$this->submitForm($edit, 'Save');
$this->assertSession()->statusMessageNotContains('Alternative text field is required.');
$this->assertSession()->statusMessageNotContains('Title field is required.');
$instance->setSetting('required', 0);
$instance->setSetting('alt_field_required', 1);
$instance->setSetting('title_field_required', 1);
$instance->save();
$edit = [
'title[0][value]' => $this->randomMachineName(),
];
$this->drupalGet('node/add/article');
$this->submitForm($edit, 'Save');
$this->assertSession()->statusMessageNotContains('Alternative text field is required.');
$this->assertSession()->statusMessageNotContains('Title field is required.');
}
/**
* Tests creating an entity while leaving the image field empty.
*
* This is tested first with edit access to the image field allowed, and then
* with it forbidden.
*
* @dataProvider providerTestEmpty
*/
public function testEmpty($field_name, $required, $cardinality, $form_element_name, $expected_page_text_when_edit_access_allowed, $expected_page_text_when_edit_access_forbidden): void {
$this->createImageField($field_name, 'node', 'article', ['cardinality' => $cardinality], ['required' => $required]);
// Test with field edit access allowed.
$this->drupalGet('node/add/article');
$this->assertSession()->fieldExists($form_element_name);
$edit = [
'title[0][value]' => 'Article with edit-access-allowed image field',
];
$this->submitForm($edit, 'Save');
$this->assertSession()->pageTextContains($expected_page_text_when_edit_access_allowed);
// Test with field edit access forbidden.
\Drupal::service('module_installer')->install(['image_access_test_hidden']);
$this->drupalGet('node/add/article');
$this->assertSession()->fieldNotExists($form_element_name);
$edit = [
'title[0][value]' => 'Article with edit-access-forbidden image field',
];
$this->submitForm($edit, 'Save');
$this->assertSession()->pageTextContains($expected_page_text_when_edit_access_forbidden);
}
/**
* Data provider for ::testEmpty()
*
* @return array
* Test cases.
*/
public static function providerTestEmpty() {
return [
'optional-single' => ['field_image', FALSE, 1, 'files[field_image_0]', 'Article Article with edit-access-allowed image field has been created.', 'Article Article with edit-access-forbidden image field has been created.'],
'optional-unlimited' => ['field_image', FALSE, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, 'files[field_image_0][]', 'Article Article with edit-access-allowed image field has been created.', 'Article Article with edit-access-forbidden image field has been created.'],
'optional-multiple-limited' => ['field_image', FALSE, 2, 'files[field_image_0][]', 'Article Article with edit-access-allowed image field has been created.', 'Article Article with edit-access-forbidden image field has been created.'],
'required-single' => ['field_image', TRUE, 1, 'files[field_image_0]', 'field_image field is required.', 'field_image field is required.'],
'required-unlimited' => ['field_image', TRUE, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED, 'files[field_image_0][]', 'field_image field is required.', 'field_image field is required.'],
// @todo Fix this discrepancy in https://www.drupal.org/project/drupal/issues/3011744.
'required-multiple-limited' => ['field_image', TRUE, 2, 'files[field_image_0][]', 'This value should not be null.', 'Article Article with edit-access-forbidden image field has been created.'],
];
}
/**
* Returns field settings.
*
* @param int[] $min_resolution
* The minimum width and height setting.
* @param int[] $max_resolution
* The maximum width and height setting.
*
* @return array
*/
protected function getFieldSettings($min_resolution, $max_resolution) {
return [
'max_resolution' => $max_resolution['width'] . 'x' . $max_resolution['height'],
'min_resolution' => $min_resolution['width'] . 'x' . $min_resolution['height'],
'alt_field' => 0,
];
}
}

View File

@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\field\Entity\FieldConfig;
/**
* Tests the image field widget.
*
* @group image
*/
class ImageFieldWidgetTest extends ImageFieldTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests file widget element.
*/
public function testWidgetElement(): void {
// Check for image widget in add/node/article page
$field_name = $this->randomMachineName();
$min_resolution = 50;
$max_resolution = 100;
$field_settings = [
'max_resolution' => $max_resolution . 'x' . $max_resolution,
'min_resolution' => $min_resolution . 'x' . $min_resolution,
'alt_field' => 0,
];
$this->createImageField($field_name, 'node', 'article', [], $field_settings, [], [], 'Image test on [site:name]');
$this->drupalGet('node/add/article');
// Verify that the image field widget is found on add/node page.
$this->assertSession()->elementExists('xpath', '//div[contains(@class, "field--widget-image-image")]');
// Verify that the image field widget limits accepted files.
$this->assertSession()->elementExists('xpath', '//input[contains(@accept, "image/*")]');
$this->assertSession()->pageTextNotContains('Image test on [site:name]');
// Check for allowed image file extensions - default.
$this->assertSession()->pageTextContains('Allowed types: png gif jpg jpeg webp.');
// Try adding to the field config an unsupported extension, should not
// appear in the allowed types.
$field_config = FieldConfig::loadByName('node', 'article', $field_name);
$field_config->setSetting('file_extensions', 'png gif jpg jpeg webp tiff')->save();
$this->drupalGet('node/add/article');
$this->assertSession()->pageTextContains('Allowed types: png gif jpg jpeg webp.');
// Add a supported extension and remove some supported ones, we should see
// the intersect of those entered in field config with those supported.
$field_config->setSetting('file_extensions', 'png jpe tiff')->save();
$this->drupalGet('node/add/article');
$this->assertSession()->pageTextContains('Allowed types: png jpe.');
}
}

View File

@@ -0,0 +1,237 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\file\Entity\File;
use Drupal\Tests\content_translation\Traits\ContentTranslationTestTrait;
use Drupal\Tests\TestFileCreationTrait;
// cspell:ignore Scarlett Johansson
/**
* Uploads images to translated nodes.
*
* @group image
*/
class ImageOnTranslatedEntityTest extends ImageFieldTestBase {
use ContentTranslationTestTrait;
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* {@inheritdoc}
*/
protected static $modules = ['language', 'content_translation', 'field_ui'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The name of the image field used in the test.
*
* @var string
*/
protected $fieldName;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// This test expects unused managed files to be marked as a temporary file.
$this->config('file.settings')->set('make_unused_managed_files_temporary', TRUE)->save();
// Create the "Basic page" node type.
// @todo Remove the disabling of new revision creation in
// https://www.drupal.org/node/1239558.
$this->drupalCreateContentType(['type' => 'basic_page', 'name' => 'Basic page', 'new_revision' => FALSE]);
// Create an image field on the "Basic page" node type.
$this->fieldName = $this->randomMachineName();
$this->createImageField($this->fieldName, 'node', 'basic_page', [], ['title_field' => 1]);
// Create and log in user.
$permissions = [
'access administration pages',
'administer content translation',
'administer content types',
'administer languages',
'administer node fields',
'create content translations',
'create basic_page content',
'edit any basic_page content',
'translate any entity',
'delete any basic_page content',
];
$admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin_user);
// Add a second and third language.
static::createLanguageFromLangcode('fr');
static::createLanguageFromLangcode('nl');
}
/**
* Tests synced file fields on translated nodes.
*/
public function testSyncedImages(): void {
// Enable translation for "Basic page" nodes.
$this->enableContentTranslation('node', 'basic_page');
static::setFieldTranslatable('node', 'basic_page', $this->fieldName, TRUE);
// Verify that the image field on the "Basic basic" node type is
// translatable.
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'basic_page');
$this->assertTrue($definitions[$this->fieldName]->isTranslatable(), 'Node image field is translatable.');
// Create a default language node.
$default_language_node = $this->drupalCreateNode(['type' => 'basic_page', 'title' => 'Lost in translation']);
// Edit the node to upload a file.
$edit = [];
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('image')[0]->uri);
$this->drupalGet('node/' . $default_language_node->id() . '/edit');
$this->submitForm($edit, 'Save');
$edit = [$this->fieldName . '[0][alt]' => 'Lost in translation image', $this->fieldName . '[0][title]' => 'Lost in translation image title'];
$this->submitForm($edit, 'Save');
$first_fid = $this->getLastFileId();
// Translate the node into French: remove the existing file.
$this->drupalGet('node/' . $default_language_node->id() . '/translations/add/en/fr');
$this->submitForm([], 'Remove');
// Upload a different file.
$edit = [];
$edit['title[0][value]'] = 'Scarlett Johansson';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('image')[1]->uri);
$this->submitForm($edit, 'Save (this translation)');
$edit = [$this->fieldName . '[0][alt]' => 'Scarlett Johansson image', $this->fieldName . '[0][title]' => 'Scarlett Johansson image title'];
$this->submitForm($edit, 'Save (this translation)');
// This inspects the HTML after the post of the translation, the image
// should be displayed on the original node.
$this->assertSession()->responseContains('alt="Lost in translation image"');
$this->assertSession()->responseContains('title="Lost in translation image title"');
$second_fid = $this->getLastFileId();
// View the translated node.
$this->drupalGet('fr/node/' . $default_language_node->id());
$this->assertSession()->responseContains('alt="Scarlett Johansson image"');
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
/** @var \Drupal\file\FileInterface $file */
// Ensure the file status of the first file permanent.
$file = File::load($first_fid);
$this->assertTrue($file->isPermanent());
// Ensure the file status of the second file is permanent.
$file = File::load($second_fid);
$this->assertTrue($file->isPermanent());
// Translate the node into dutch: remove the existing file.
$this->drupalGet('node/' . $default_language_node->id() . '/translations/add/en/nl');
$this->submitForm([], 'Remove');
// Upload a different file.
$edit = [];
$edit['title[0][value]'] = 'Ada Lovelace';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('image')[2]->uri);
$this->submitForm($edit, 'Save (this translation)');
$edit = [$this->fieldName . '[0][alt]' => 'Ada Lovelace image', $this->fieldName . '[0][title]' => 'Ada Lovelace image title'];
$this->submitForm($edit, 'Save (this translation)');
$third_fid = $this->getLastFileId();
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
// Ensure the first file is untouched.
$file = File::load($first_fid);
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
// This inspects the HTML after the post of the translation, the image
// should be displayed on the original node.
$this->assertSession()->responseContains('alt="Lost in translation image"');
$this->assertSession()->responseContains('title="Lost in translation image title"');
// View the translated node.
$this->drupalGet('nl/node/' . $default_language_node->id());
$this->assertSession()->responseContains('alt="Ada Lovelace image"');
$this->assertSession()->responseContains('title="Ada Lovelace image title"');
// Ensure the file status of the second file is permanent.
$file = File::load($second_fid);
$this->assertTrue($file->isPermanent());
// Ensure the file status of the third file is permanent.
$file = File::load($third_fid);
$this->assertTrue($file->isPermanent());
// Edit the second translation: remove the existing file.
$this->drupalGet('fr/node/' . $default_language_node->id() . '/edit');
$this->submitForm([], 'Remove');
// Upload a different file.
$edit = [];
$edit['title[0][value]'] = 'Giovanni Ribisi';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('image')[3]->uri);
$this->submitForm($edit, 'Save (this translation)');
$name = $this->fieldName . '[0][alt]';
$edit = [$name => 'Giovanni Ribisi image'];
$this->submitForm($edit, 'Save (this translation)');
$replaced_second_fid = $this->getLastFileId();
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
// Ensure the first and third files are untouched.
$file = File::load($first_fid);
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
$file = File::load($third_fid);
$this->assertTrue($file->isPermanent());
// Ensure the file status of the replaced second file is permanent.
$file = File::load($replaced_second_fid);
$this->assertTrue($file->isPermanent());
// Delete the third translation.
$this->drupalGet('nl/node/' . $default_language_node->id() . '/delete');
$this->submitForm([], 'Delete Dutch translation');
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
// Ensure the first and replaced second files are untouched.
$file = File::load($first_fid);
$this->assertTrue($file->isPermanent(), 'First file still exists and is permanent.');
$file = File::load($replaced_second_fid);
$this->assertTrue($file->isPermanent());
// Ensure the file status of the third file is now temporary.
$file = File::load($third_fid);
$this->assertTrue($file->isTemporary());
// Delete the all translations.
$this->drupalGet('node/' . $default_language_node->id() . '/delete');
$this->submitForm([], 'Delete all translations');
\Drupal::entityTypeManager()->getStorage('file')->resetCache();
// Ensure the file status of the all files are now temporary.
$file = File::load($first_fid);
$this->assertTrue($file->isTemporary(), 'First file still exists and is temporary.');
$file = File::load($replaced_second_fid);
$this->assertTrue($file->isTemporary());
}
}

View File

@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
/**
* Tests image style deletion using the UI.
*
* @group image
*/
class ImageStyleDeleteTest extends ImageFieldTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create an image field 'foo' having the image style 'medium' as widget
// preview and as formatter.
$this->createImageField('foo', 'node', 'page', [], [], ['preview_image_style' => 'medium'], ['image_style' => 'medium']);
}
/**
* Tests image style deletion.
*/
public function testDelete(): void {
$this->drupalGet('admin/config/media/image-styles/manage/medium/delete');
// Checks that the 'replacement' select element is displayed.
$this->assertSession()->fieldExists('replacement');
// Checks that UI messages are correct.
$this->assertSession()->pageTextContains("If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.");
$this->assertSession()->pageTextNotContains("All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.");
// Delete 'medium' image style but replace it with 'thumbnail'. This style
// is involved in 'node.page.default' display view and form.
$this->submitForm(['replacement' => 'thumbnail'], 'Delete');
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
$view_display = EntityViewDisplay::load('node.page.default');
// Checks that the formatter setting is replaced.
$this->assertNotNull($component = $view_display->getComponent('foo'));
$this->assertSame('thumbnail', $component['settings']['image_style']);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = EntityFormDisplay::load('node.page.default');
// Check that the widget setting is replaced.
$this->assertNotNull($component = $form_display->getComponent('foo'));
$this->assertSame('thumbnail', $component['settings']['preview_image_style']);
$this->drupalGet('admin/config/media/image-styles/manage/thumbnail/delete');
// Checks that the 'replacement' select element is displayed.
$this->assertSession()->fieldExists('replacement');
// Checks that UI messages are correct.
$this->assertSession()->pageTextContains("If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.");
$this->assertSession()->pageTextNotContains("All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.");
// Delete 'thumbnail' image style. Provide no replacement.
$this->submitForm([], 'Delete');
$view_display = EntityViewDisplay::load('node.page.default');
// Checks that the formatter setting is disabled.
$this->assertNull($view_display->getComponent('foo'));
$this->assertNotNull($view_display->get('hidden')['foo']);
// Checks that widget setting is preserved with the image preview disabled.
$form_display = EntityFormDisplay::load('node.page.default');
$this->assertNotNull($widget = $form_display->getComponent('foo'));
$this->assertSame('', $widget['settings']['preview_image_style']);
$this->drupalGet('admin/config/media/image-styles/manage/wide/delete');
// Checks that the 'replacement' select element is displayed.
$this->assertSession()->fieldExists('replacement');
// Checks that UI messages are correct.
$this->assertSession()->pageTextContains("If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.");
$this->assertSession()->pageTextNotContains("All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.");
// Delete 'wide' image style. Provide no replacement.
$this->submitForm([], 'Delete');
// Now, there's only one image style configured on the system: 'large'.
$this->drupalGet('admin/config/media/image-styles/manage/large/delete');
// Checks that the 'replacement' select element is not displayed.
$this->assertSession()->fieldNotExists('replacement');
// Checks that UI messages are correct.
$this->assertSession()->pageTextNotContains("If this style is in use on the site, you may select another style to replace it. All images that have been generated for this style will be permanently deleted. If no replacement style is selected, the dependent configurations might need manual reconfiguration.");
$this->assertSession()->pageTextContains("All images that have been generated for this style will be permanently deleted. The dependent configurations might need manual reconfiguration.");
}
}

View File

@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\Url;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\BrowserTestBase;
/**
* Tests access control for downloading image styles.
*
* @group image
*/
class ImageStyleDownloadAccessControlTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['image'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The file system.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* The image style.
*
* @var \Drupal\image\ImageStyleInterface
*/
protected $style;
/**
* {@inheritdoc}
*/
protected function prepareEnvironment(): void {
parent::prepareEnvironment();
// @see static::testPrivateSchemeWithinPublic()
$this->privateFilesDirectory = $this->publicFilesDirectory . '/private';
}
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->fileSystem = $this->container->get('file_system');
$this->style = ImageStyle::create([
'name' => 'style_foo',
'label' => $this->randomString(),
]);
$this->style->save();
// Access control must be respected even when this setting is TRUE.
$this->config('image.settings')
->set('allow_insecure_derivatives', TRUE)
->save();
}
/**
* Ensures that private:// access is forbidden through image.style_public.
*/
public function testPrivateThroughPublicRoute(): void {
$this->fileSystem->copy(\Drupal::root() . '/core/tests/fixtures/files/image-1.png', 'private://image.png');
// Manually create the file record for the private:// file as we want it
// to be temporary to pass hook_download() acl's.
$values = [
'uid' => $this->rootUser->id(),
'status' => 0,
'filename' => 'image.png',
'uri' => 'private://image.png',
'filesize' => filesize('private://image.png'),
'filemime' => 'image/png',
];
$private_file = File::create($values);
$private_file->save();
$this->assertNotFalse(getimagesize($private_file->getFileUri()));
$token = $this->style->getPathToken('private://image.png');
$public_route_private_scheme = Url::fromRoute(
'image.style_public',
[
'image_style' => $this->style->id(),
'scheme' => 'private',
],
)
->setAbsolute(TRUE);
$generate_url = $public_route_private_scheme->toString() . '/image.png?itok=' . $token;
$this->drupalLogin($this->rootUser);
$this->drupalGet($generate_url);
$this->drupalGet(PublicStream::basePath() . '/styles/' . $this->style->id() . '/private/image.png');
$this->assertSession()->statusCodeEquals(403);
}
/**
* Ensures that public:// access is forbidden through image.style.private.
*/
public function testPublicThroughPrivateRoute(): void {
$this->fileSystem->copy(\Drupal::root() . '/core/tests/fixtures/files/image-1.png', 'public://image.png');
$token = $this->style->getPathToken('public://image.png');
$private_route_public_scheme = Url::fromRoute(
'image.style_private',
[
'image_style' => $this->style->id(),
'scheme' => 'public',
],
)
->setAbsolute(TRUE);
$generate_url = $private_route_public_scheme->toString() . '/image.png?itok=' . $token;
$this->drupalGet($generate_url);
$this->assertSession()->statusCodeEquals(403);
}
}

View File

@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests flushing of image styles.
*
* @group image
*/
class ImageStyleFlushTest extends ImageFieldTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Given an image style and a wrapper, generate an image.
*/
public function createSampleImage($style, $wrapper) {
static $file;
if (!isset($file)) {
$files = $this->drupalGetTestFiles('image');
$file = reset($files);
}
// Make sure we have an image in our wrapper testing file directory.
$source_uri = \Drupal::service('file_system')->copy($file->uri, $wrapper . '://');
// Build the derivative image.
$derivative_uri = $style->buildUri($source_uri);
$derivative = $style->createDerivative($source_uri, $derivative_uri);
return $derivative ? $derivative_uri : FALSE;
}
/**
* Count the number of images currently created for a style in a wrapper.
*/
public function getImageCount($style, $wrapper) {
$count = 0;
if (is_dir($wrapper . '://styles/' . $style->id())) {
$count = count(\Drupal::service('file_system')->scanDirectory($wrapper . '://styles/' . $style->id(), '/.*/'));
}
return $count;
}
/**
* General test to flush a style.
*/
public function testFlush(): void {
// Setup a style to be created and effects to add to it.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomString();
$style_path = 'admin/config/media/image-styles/manage/' . $style_name;
$effect_edits = [
'image_resize' => [
'data[width]' => 100,
'data[height]' => 101,
],
'image_scale' => [
'data[width]' => 110,
'data[height]' => 111,
'data[upscale]' => 1,
],
];
// Add style form.
$edit = [
'name' => $style_name,
'label' => $style_label,
];
$this->drupalGet('admin/config/media/image-styles/add');
$this->submitForm($edit, 'Create new style');
// Add each sample effect to the style.
foreach ($effect_edits as $effect => $edit) {
// Add the effect.
$this->drupalGet($style_path);
$this->submitForm(['new' => $effect], 'Add');
if (!empty($edit)) {
$this->submitForm($edit, 'Add effect');
}
}
// Load the saved image style.
$style = ImageStyle::load($style_name);
// Create an image for the 'public' wrapper.
$image_path = $this->createSampleImage($style, 'public');
// Expecting to find 2 images, one is the sample.png image shown in
// image style preview.
$this->assertEquals(2, $this->getImageCount($style, 'public'), "Image style {$style->label()} image $image_path successfully generated.");
// Create an image for the 'private' wrapper.
$image_path = $this->createSampleImage($style, 'private');
$this->assertEquals(1, $this->getImageCount($style, 'private'), "Image style {$style->label()} image $image_path successfully generated.");
// Remove the 'image_scale' effect and updates the style, which in turn
// forces an image style flush.
$style_path = 'admin/config/media/image-styles/manage/' . $style->id();
$uuids = [];
foreach ($style->getEffects() as $uuid => $effect) {
$uuids[$effect->getPluginId()] = $uuid;
}
$this->drupalGet($style_path . '/effects/' . $uuids['image_scale'] . '/delete');
$this->submitForm([], 'Delete');
$this->assertSession()->statusCodeEquals(200);
$this->drupalGet($style_path);
$this->submitForm([], 'Save');
$this->assertSession()->statusCodeEquals(200);
// Post flush, expected 1 image in the 'public' wrapper (sample.png).
$this->assertEquals(1, $this->getImageCount($style, 'public'), "Image style {$style->label()} flushed correctly for public wrapper.");
// Post flush, expected no image in the 'private' wrapper.
$this->assertEquals(0, $this->getImageCount($style, 'private'), "Image style {$style->label()} flushed correctly for private wrapper.");
$state = \Drupal::state();
$state->set('image_module_test_image_style_flush.called', FALSE);
$style->flush();
$this->assertNull($state->get('image_module_test_image_style_flush.called'));
$style->flush('/made/up/path');
$this->assertSame('/made/up/path', $state->get('image_module_test_image_style_flush.called'));
}
}

View File

@@ -0,0 +1,348 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional;
use Drupal\Core\File\FileExists;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\image\Entity\ImageStyle;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the functions for generating paths and URLs for image styles.
*
* @group image
*/
class ImageStylesPathAndUrlTest extends BrowserTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['image', 'image_module_test', 'language'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The image style.
*
* @var \Drupal\image\ImageStyleInterface
*/
protected $style;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->style = ImageStyle::create([
'name' => 'style_foo',
'label' => $this->randomString(),
]);
$this->style->save();
// Create a new language.
ConfigurableLanguage::createFromLangcode('fr')->save();
}
/**
* Tests \Drupal\image\ImageStyleInterface::buildUri().
*/
public function testImageStylePath(): void {
$scheme = 'public';
$actual = $this->style->buildUri("$scheme://foo/bar.gif");
$expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
$this->assertEquals($expected, $actual, 'Got the path for a file URI.');
$actual = $this->style->buildUri('foo/bar.gif');
$expected = "$scheme://styles/" . $this->style->id() . "/$scheme/foo/bar.gif";
$this->assertEquals($expected, $actual, 'Got the path for a relative file path.');
}
/**
* Tests an image style URL using the "public://" scheme.
*/
public function testImageStyleUrlAndPathPublic(): void {
$this->doImageStyleUrlAndPathTests('public');
}
/**
* Tests an image style URL using the "private://" scheme.
*/
public function testImageStyleUrlAndPathPrivate(): void {
$this->doImageStyleUrlAndPathTests('private');
}
/**
* Tests an image style URL with the "public://" scheme and unclean URLs.
*/
public function testImageStyleUrlAndPathPublicUnclean(): void {
$this->doImageStyleUrlAndPathTests('public', FALSE);
}
/**
* Tests an image style URL with the "private://" schema and unclean URLs.
*/
public function testImageStyleUrlAndPathPrivateUnclean(): void {
$this->doImageStyleUrlAndPathTests('private', FALSE);
}
/**
* Tests an image style URL with the "public://" schema and language prefix.
*/
public function testImageStyleUrlAndPathPublicLanguage(): void {
$this->doImageStyleUrlAndPathTests('public', TRUE, TRUE, 'fr');
}
/**
* Tests an image style URL with the "private://" schema and language prefix.
*/
public function testImageStyleUrlAndPathPrivateLanguage(): void {
$this->doImageStyleUrlAndPathTests('private', TRUE, TRUE, 'fr');
}
/**
* Tests an image style URL with a file URL that has an extra slash in it.
*/
public function testImageStyleUrlExtraSlash(): void {
$this->doImageStyleUrlAndPathTests('public', TRUE, TRUE);
}
/**
* Test an image style URL with a private file that also gets converted.
*/
public function testImageStylePrivateWithConversion(): void {
// Add the "convert" image style effect to our style.
$this->style->addImageEffect([
'uuid' => '',
'id' => 'image_convert',
'weight' => 1,
'data' => [
'extension' => 'jpeg',
],
]);
$this->doImageStyleUrlAndPathTests('private');
}
/**
* Tests that an invalid source image returns a 404.
*/
public function testImageStyleUrlForMissingSourceImage(): void {
$non_existent_uri = 'public://foo.png';
$generated_url = $this->style->buildUrl($non_existent_uri);
$this->drupalGet($generated_url);
$this->assertSession()->statusCodeEquals(404);
}
/**
* Tests building an image style URL.
*/
public function doImageStyleUrlAndPathTests($scheme, $clean_url = TRUE, $extra_slash = FALSE, $langcode = FALSE) {
$this->prepareRequestForGenerator($clean_url);
// Make the default scheme neither "public" nor "private" to verify the
// functions work for other than the default scheme.
$this->config('system.file')->set('default_scheme', 'temporary')->save();
// Create the directories for the styles.
$directory = $scheme . '://styles/' . $this->style->id();
$status = \Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY);
$this->assertNotFalse($status, 'Created the directory for the generated images for the test style.');
// Override the language to build the URL for the correct language.
if ($langcode) {
$language_manager = \Drupal::service('language_manager');
$language = $language_manager->getLanguage($langcode);
$language_manager->setConfigOverrideLanguage($language);
}
// Create a working copy of the file.
$files = $this->drupalGetTestFiles('image');
$file = array_shift($files);
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$original_uri = $file_system->copy($file->uri, $scheme . '://', FileExists::Rename);
// Let the image_module_test module know about this file, so it can claim
// ownership in hook_file_download().
\Drupal::state()->set('image.test_file_download', $original_uri);
$this->assertNotFalse($original_uri, 'Created the generated image file.');
// Get the URL of a file that has not been generated and try to create it.
$generated_uri = $this->style->buildUri($original_uri);
$this->assertFileDoesNotExist($generated_uri);
$generate_url = $this->style->buildUrl($original_uri, $clean_url);
// Make sure that language prefix is never added to the image style URL.
if ($langcode) {
$this->assertStringNotContainsString("/$langcode/", $generate_url, 'Langcode was not found in the image style URL.');
}
// Ensure that the tests still pass when the file is generated by accessing
// a poorly constructed (but still valid) file URL that has an extra slash
// in it.
if ($extra_slash) {
$modified_uri = str_replace('://', ':///', $original_uri);
$this->assertNotEquals($original_uri, $modified_uri, 'An extra slash was added to the generated file URI.');
$generate_url = $this->style->buildUrl($modified_uri, $clean_url);
}
if (!$clean_url) {
$this->assertStringContainsString('index.php/', $generate_url, 'When using non-clean URLS, the system path contains the script name.');
}
// Add some extra chars to the token.
$this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
$this->assertSession()->statusCodeEquals(404);
// Change the parameter name so the token is missing.
$this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrong_parameter=', $generate_url));
$this->assertSession()->statusCodeEquals(404);
// Check that the generated URL is the same when we pass in a relative path
// rather than a URI. We need to temporarily switch the default scheme to
// match the desired scheme before testing this, then switch it back to the
// "temporary" scheme used throughout this test afterwards.
$this->config('system.file')->set('default_scheme', $scheme)->save();
$relative_path = StreamWrapperManager::getTarget($original_uri);
$generate_url_from_relative_path = $this->style->buildUrl($relative_path, $clean_url);
$this->assertEquals($generate_url, $generate_url_from_relative_path);
$this->config('system.file')->set('default_scheme', 'temporary')->save();
// Fetch the URL that generates the file.
$this->drupalGet($generate_url);
$this->assertSession()->statusCodeEquals(200);
$this->assertFileExists($generated_uri);
// assertRaw can't be used with string containing non UTF-8 chars.
$this->assertNotEmpty(file_get_contents($generated_uri), 'URL returns expected file.');
$image = $this->container->get('image.factory')->get($generated_uri);
$this->assertSession()->responseHeaderEquals('Content-Type', $image->getMimeType());
$this->assertSession()->responseHeaderEquals('Content-Length', (string) $image->getFileSize());
// Check that we did not download the original file.
$original_image = $this->container->get('image.factory')
->get($original_uri);
$this->assertSession()->responseHeaderNotEquals('Content-Length', (string) $original_image->getFileSize());
if ($scheme == 'private') {
$this->assertSession()->responseHeaderEquals('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
// Check that Cache-Control header contains 'no-cache' to prevent caching.
$this->assertSession()->responseHeaderContains('Cache-Control', 'no-cache');
$this->assertSession()->responseHeaderEquals('X-Image-Owned-By', 'image_module_test');
// Make sure that a second request to the already existing derivative
// works too.
$this->drupalGet($generate_url);
$this->assertSession()->statusCodeEquals(200);
// Check that the second request also returned the generated image.
$this->assertSession()->responseHeaderEquals('Content-Length', (string) $image->getFileSize());
// Check that we did not download the original file.
$this->assertSession()->responseHeaderNotEquals('Content-Length', (string) $original_image->getFileSize());
// Make sure that access is denied for existing style files if we do not
// have access.
\Drupal::state()->delete('image.test_file_download');
$this->drupalGet($generate_url);
$this->assertSession()->statusCodeEquals(403);
// Repeat this with a different file that we do not have access to and
// make sure that access is denied.
$file_no_access = array_shift($files);
$original_uri_no_access = $file_system->copy($file_no_access->uri, $scheme . '://', FileExists::Rename);
$generated_uri_no_access = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . $file_system->basename($original_uri_no_access);
$this->assertFileDoesNotExist($generated_uri_no_access);
$generate_url_no_access = $this->style->buildUrl($original_uri_no_access);
$this->drupalGet($generate_url_no_access);
$this->assertSession()->statusCodeEquals(403);
// Verify that images are not appended to the response.
// Currently this test only uses PNG images.
if (!str_contains($generate_url, '.png')) {
$this->fail('Confirming that private image styles are not appended require PNG file.');
}
else {
// Check for PNG-Signature
// (cf. http://www.libpng.org/pub/png/book/chapter08.html#png.ch08.div.2)
// in the response body.
$raw = $this->getSession()->getPage()->getContent();
$this->assertStringNotContainsString(chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10), $raw);
}
}
else {
$this->assertSession()->responseHeaderEquals('Expires', 'Sun, 19 Nov 1978 05:00:00 GMT');
$this->assertSession()->responseHeaderNotContains('Cache-Control', 'no-cache');
if ($clean_url) {
// Add some extra chars to the token.
$this->drupalGet(str_replace(IMAGE_DERIVATIVE_TOKEN . '=', IMAGE_DERIVATIVE_TOKEN . '=Zo', $generate_url));
$this->assertSession()->statusCodeEquals(200);
}
}
// Allow insecure image derivatives to be created for the remainder of this
// test.
$this->config('image.settings')
->set('allow_insecure_derivatives', TRUE)
->save();
// Create another working copy of the file.
$files = $this->drupalGetTestFiles('image');
$file = array_shift($files);
$original_uri = $file_system->copy($file->uri, $scheme . '://', FileExists::Rename);
// Let the image_module_test module know about this file, so it can claim
// ownership in hook_file_download().
\Drupal::state()->set('image.test_file_download', $original_uri);
// Suppress the security token in the URL, then get the URL of a file that
// has not been created and try to create it. Check that the security token
// is not present in the URL but that the image is still accessible.
$this->config('image.settings')->set('suppress_itok_output', TRUE)->save();
$generated_uri = $this->style->buildUri($original_uri);
$this->assertFileDoesNotExist($generated_uri);
$generate_url = $this->style->buildUrl($original_uri, $clean_url);
$this->assertStringNotContainsString(IMAGE_DERIVATIVE_TOKEN . '=', $generate_url, 'The security token does not appear in the image style URL.');
$this->drupalGet($generate_url);
$this->assertSession()->statusCodeEquals(200);
// Stop suppressing the security token in the URL.
$this->config('image.settings')->set('suppress_itok_output', FALSE)->save();
// Ensure allow_insecure_derivatives is enabled.
$this->assertEquals(TRUE, $this->config('image.settings')->get('allow_insecure_derivatives'));
// Check that a security token is still required when generating a second
// image derivative using the first one as a source.
$nested_url = $this->style->buildUrl($generated_uri, $clean_url);
$matches_expected_url_format = (boolean) preg_match('/styles\/' . $this->style->id() . '\/' . $scheme . '\/styles\/' . $this->style->id() . '\/' . $scheme . '/', $nested_url);
$this->assertTrue($matches_expected_url_format, "URL for a derivative of an image style matches expected format.");
$nested_url_with_wrong_token = str_replace(IMAGE_DERIVATIVE_TOKEN . '=', 'wrong_parameter=', $nested_url);
$this->drupalGet($nested_url_with_wrong_token);
$this->assertSession()->statusCodeEquals(404);
// Check that this restriction cannot be bypassed by adding extra slashes
// to the URL.
$this->drupalGet(substr_replace($nested_url_with_wrong_token, '//styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
$this->assertSession()->statusCodeEquals(404);
$this->drupalGet(substr_replace($nested_url_with_wrong_token, '////styles/', strrpos($nested_url_with_wrong_token, '/styles/'), strlen('/styles/')));
$this->assertSession()->statusCodeEquals(404);
// Make sure the image can still be generated if a correct token is used.
$this->drupalGet($nested_url);
$this->assertSession()->statusCodeEquals(200);
// Check that requesting a nonexistent image does not create any new
// directories in the file system.
$directory = $scheme . '://styles/' . $this->style->id() . '/' . $scheme . '/' . $this->randomMachineName();
$this->drupalGet(\Drupal::service('file_url_generator')->generateAbsoluteString($directory . '/' . $this->randomString()));
$this->assertDirectoryDoesNotExist($directory);
}
}

View File

@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
/**
* @group rest
*/
class ImageStyleJsonAnonTest extends ImageStyleResourceTestBase {
use AnonResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
/**
* @group rest
*/
class ImageStyleJsonBasicAuthTest extends ImageStyleResourceTestBase {
use BasicAuthResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
/**
* @group rest
*/
class ImageStyleJsonCookieTest extends ImageStyleResourceTestBase {
use CookieResourceTestTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'json';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'application/json';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
}

View File

@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\rest\Functional\EntityResource\ConfigEntityResourceTestBase;
/**
* ResourceTestBase for ImageStyle entity.
*/
abstract class ImageStyleResourceTestBase extends ConfigEntityResourceTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'image_style';
/**
* The ImageStyle entity.
*
* @var \Drupal\image\ImageStyleInterface
*/
protected $entity;
/**
* The effect UUID.
*
* @var string
*/
protected $effectUuid;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
$this->grantPermissionsToTestedRole(['administer image styles']);
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "Camelids" image style.
$camelids = ImageStyle::create([
'name' => 'camelids',
'label' => 'Camelids',
]);
// Add an image effect.
$effect = [
'id' => 'image_scale_and_crop',
'data' => [
'anchor' => 'center-center',
'width' => 120,
'height' => 121,
],
'weight' => 0,
];
$this->effectUuid = $camelids->addImageEffect($effect);
$camelids->save();
return $camelids;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
return [
'dependencies' => [],
'effects' => [
$this->effectUuid => [
'uuid' => $this->effectUuid,
'id' => 'image_scale_and_crop',
'weight' => 0,
'data' => [
'anchor' => 'center-center',
'width' => 120,
'height' => 121,
],
],
],
'label' => 'Camelids',
'langcode' => 'en',
'name' => 'camelids',
'status' => TRUE,
'uuid' => $this->entity->uuid(),
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
// @todo Update in https://www.drupal.org/node/2300677.
return [];
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessMessage($method) {
return "The 'administer image styles' permission is required.";
}
}

View File

@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\AnonResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class ImageStyleXmlAnonTest extends ImageStyleResourceTestBase {
use AnonResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
public function testGet(): void {
// @todo Remove this method override in https://www.drupal.org/node/2905655
$this->markTestSkipped();
}
}

View File

@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\BasicAuthResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class ImageStyleXmlBasicAuthTest extends ImageStyleResourceTestBase {
use BasicAuthResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['basic_auth'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'basic_auth';
/**
* {@inheritdoc}
*/
public function testGet(): void {
// @todo Remove this method override in https://www.drupal.org/node/2905655
$this->markTestSkipped();
}
}

View File

@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Functional\Rest;
use Drupal\Tests\rest\Functional\CookieResourceTestTrait;
use Drupal\Tests\rest\Functional\EntityResource\XmlEntityNormalizationQuirksTrait;
/**
* @group rest
*/
class ImageStyleXmlCookieTest extends ImageStyleResourceTestBase {
use CookieResourceTestTrait;
use XmlEntityNormalizationQuirksTrait;
/**
* {@inheritdoc}
*/
protected static $format = 'xml';
/**
* {@inheritdoc}
*/
protected static $mimeType = 'text/xml; charset=UTF-8';
/**
* {@inheritdoc}
*/
protected static $auth = 'cookie';
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* {@inheritdoc}
*/
public function testGet(): void {
// @todo Remove this method override in https://www.drupal.org/node/2905655
$this->markTestSkipped();
}
}

View File

@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\FunctionalJavascript;
use Drupal\image\Entity\ImageStyle;
/**
* Tests creation, deletion, and editing of image styles and effects.
*
* @group image
*/
class ImageAdminStylesTest extends ImageFieldTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests editing Ajax-enabled image effect forms.
*/
public function testAjaxEnabledEffectForm(): void {
$admin_path = 'admin/config/media/image-styles';
// Setup a style to be created and effects to add to it.
$style_name = $this->randomMachineName(10);
$style_label = $this->randomString();
$style_path = $admin_path . '/manage/' . $style_name;
$effect_edit = [
'data[test_parameter]' => 100,
];
// Add style form.
$page = $this->getSession()->getPage();
$assert = $this->assertSession();
$this->drupalGet($admin_path . '/add');
$page->findField('label')->setValue($style_label);
$assert->waitForElementVisible('named', ['button', 'Edit'])->press();
$assert->waitForElementVisible('named', ['id_or_name', 'name'])->setValue($style_name);
$page->pressButton('Create new style');
$assert->statusMessageContains("Style $style_label was created.", 'status');
// Add two Ajax-enabled test effects.
$this->drupalGet($style_path);
$this->submitForm(['new' => 'image_module_test_ajax'], 'Add');
$this->submitForm($effect_edit, 'Add effect');
$this->drupalGet($style_path);
$this->submitForm(['new' => 'image_module_test_ajax'], 'Add');
$this->submitForm($effect_edit, 'Add effect');
// Load the saved image style.
$style = ImageStyle::load($style_name);
// Edit back the effects.
foreach ($style->getEffects() as $uuid => $effect) {
$effect_path = $admin_path . '/manage/' . $style_name . '/effects/' . $uuid;
$this->drupalGet($effect_path);
$page->findField('data[test_parameter]')->setValue(111);
$ajax_value = $page->find('css', '#ajax-value')->getText();
$this->assertSame('Ajax value bar', $ajax_value);
$this->getSession()->getPage()->pressButton('Ajax refresh');
$this->assertTrue($page->waitFor(10, function ($page) {
$ajax_value = $page->find('css', '#ajax-value')->getText();
return (bool) preg_match('/^Ajax value [0-9.]+ [0-9.]+$/', $ajax_value);
}));
$page->pressButton('Update effect');
$assert->statusMessageContains('The image effect was successfully applied.', 'status');
}
}
}

View File

@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\TestFileCreationTrait;
/**
* This class provides methods specifically for testing Image's field handling.
*/
abstract class ImageFieldTestBase extends WebDriverTestBase {
use ImageFieldCreationTrait;
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'node',
'image',
'field_ui',
'image_module_test',
];
/**
* A user with permissions to administer content types and image styles.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create Basic page and Article node types.
if ($this->profile !== 'standard') {
$this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
}
$this->adminUser = $this->drupalCreateUser([
'access content',
'access administration pages',
'administer site configuration',
'administer content types',
'administer node fields',
'administer nodes',
'create article content',
'edit any article content',
'delete any article content',
'administer image styles',
'administer node display',
]);
$this->drupalLogin($this->adminUser);
}
}

View File

@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\FunctionalJavascript;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
/**
* Tests validation functions such as min/max dimensions.
*
* @group image
*/
class ImageFieldValidateTest extends ImageFieldTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests the validation message is displayed only once for ajax uploads.
*/
public function testAJAXValidationMessage(): void {
$field_name = $this->randomMachineName();
$this->createImageField($field_name, 'node', 'article', ['cardinality' => -1]);
$this->drupalGet('node/add/article');
/** @var \Drupal\file\FileInterface[] $text_files */
$text_files = $this->drupalGetTestFiles('text');
$text_file = reset($text_files);
$field = $this->getSession()->getPage()->findField('files[' . $field_name . '_0][]');
$field->attachFile($this->container->get('file_system')->realpath($text_file->uri));
$this->assertSession()->waitForElement('css', '.messages--error');
// Verify that Ajax validation messages are displayed only once.
$this->assertSession()->elementsCount('xpath', '//div[contains(@class, "messages--error")]', 1);
}
/**
* Tests that image field validation works with other form submit handlers.
*/
public function testFriendlyAjaxValidation(): void {
// Add a custom field to the Article content type that contains an AJAX
// handler on a select field.
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_dummy_select',
'type' => 'image_module_test_dummy_ajax',
'entity_type' => 'node',
'cardinality' => 1,
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'entity_type' => 'node',
'bundle' => 'article',
'field_name' => 'field_dummy_select',
'label' => 'Dummy select',
])->save();
\Drupal::entityTypeManager()
->getStorage('entity_form_display')
->load('node.article.default')
->setComponent(
'field_dummy_select',
[
'type' => 'image_module_test_dummy_ajax_widget',
'weight' => 1,
])
->save();
// Then, add an image field.
$this->createImageField('field_dummy_image', 'node', 'article');
// Open an article and trigger the AJAX handler.
$this->drupalGet('node/add/article');
$id = $this->getSession()->getPage()->find('css', '[name="form_build_id"]')->getValue();
$field = $this->getSession()->getPage()->findField('field_dummy_select[select_widget]');
$field->setValue('bam');
// Make sure that the operation did not end with an exception.
$this->assertSession()->waitForElement('css', "[name='form_build_id']:not([value='$id'])");
}
}

View File

@@ -0,0 +1,77 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\FunctionalJavascript;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\node\Entity\Node;
use Drupal\Tests\image\Kernel\ImageFieldCreationTrait;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the image field widget support multiple upload correctly.
*
* @group image
*/
class ImageFieldWidgetMultipleTest extends WebDriverTestBase {
use ImageFieldCreationTrait;
use TestFileCreationTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['node', 'field_ui', 'image'];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* Tests image widget element support multiple upload correctly.
*/
public function testWidgetElementMultipleUploads(): void {
$image_factory = \Drupal::service('image.factory');
$file_system = \Drupal::service('file_system');
$web_driver = $this->getSession()->getDriver();
$this->drupalCreateContentType(['type' => 'article', 'name' => 'Article']);
$field_name = 'images';
$storage_settings = ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED];
$field_settings = ['alt_field_required' => 0];
$this->createImageField($field_name, 'node', 'article', $storage_settings, $field_settings);
$this->drupalLogin($this->drupalCreateUser(['access content', 'create article content']));
$this->drupalGet('node/add/article');
$this->assertSession()->fieldExists('title[0][value]')->setValue('Test');
$images = $this->getTestFiles('image');
$images = array_slice($images, 0, 5);
$paths = [];
foreach ($images as $image) {
$paths[] = $file_system->realpath($image->uri);
}
$remote_paths = [];
foreach ($paths as $path) {
$remote_paths[] = $web_driver->uploadFileAndGetRemoteFilePath($path);
}
$multiple_field = $this->assertSession()->elementExists('xpath', '//input[@multiple]');
$multiple_field->setValue(implode("\n", $remote_paths));
$this->assertSession()->waitForElementVisible('css', '[data-drupal-selector="edit-images-4-preview"]');
$this->getSession()->getPage()->findButton('Save')->click();
$node = Node::load(1);
foreach ($paths as $delta => $path) {
$node_image = $node->{$field_name}[$delta];
$original_image = $image_factory->get($path);
$this->assertEquals($original_image->getWidth(), $node_image->width, "Correct width of image #$delta");
$this->assertEquals($original_image->getHeight(), $node_image->height, "Correct height of image #$delta");
}
}
}

View File

@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\File\FileExists;
use Drupal\file\Entity\File;
use Drupal\file\FileRepository;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests the file move function for images and image styles.
*
* @group image
*/
class FileMoveTest extends KernelTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* {@inheritdoc}
*/
protected static $modules = [
'file',
'image',
'system',
'user',
];
/**
* The file repository service.
*/
protected FileRepository $fileRepository;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installConfig(['system']);
$this->installEntitySchema('file');
$this->installEntitySchema('user');
$this->installSchema('file', ['file_usage']);
ImageStyle::create([
'name' => 'main_style',
'label' => 'Main',
])->save();
$this->fileRepository = $this->container->get('file.repository');
}
/**
* Tests moving a randomly generated image.
*/
public function testNormal(): void {
// Pick a file for testing.
$file = File::create((array) current($this->drupalGetTestFiles('image')));
// Create derivative image.
$styles = ImageStyle::loadMultiple();
$style = reset($styles);
$original_uri = $file->getFileUri();
$derivative_uri = $style->buildUri($original_uri);
$style->createDerivative($original_uri, $derivative_uri);
// Check if derivative image exists.
$this->assertFileExists($derivative_uri);
// Clone the object, so we don't have to worry about the function changing
// our reference copy.
$desired_filepath = 'public://' . $this->randomMachineName();
$result = $this->fileRepository->move(clone $file, $desired_filepath, FileExists::Error);
// Check if image has been moved.
$this->assertFileExists($result->getFileUri());
// Check if derivative image has been flushed.
$this->assertFileDoesNotExist($derivative_uri);
}
}

View File

@@ -0,0 +1,247 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Form\FormState;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\Form\ImageEffectEditForm;
use Drupal\Tests\Traits\Core\Image\ToolkitTestTrait;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests image effects.
*
* @group image
*/
class ImageEffectsTest extends KernelTestBase {
use ToolkitTestTrait;
/**
* The image effect plugin manager service.
*
* @var \Drupal\image\ImageEffectManager
*/
protected $imageEffectPluginManager;
/**
* {@inheritdoc}
*/
protected static $modules = [
'image',
'image_module_test',
'image_test',
'system',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->imageEffectPluginManager = $this->container->get('plugin.manager.image.effect');
}
/**
* Tests the 'image_resize' effect.
*/
public function testResizeEffect(): void {
$this->assertImageEffect(['resize'], 'image_resize', [
'width' => 1,
'height' => 2,
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// Width was passed correctly.
$this->assertEquals(1, $calls['resize'][0][0]);
// Height was passed correctly.
$this->assertEquals(2, $calls['resize'][0][1]);
}
/**
* Tests the 'image_scale' effect.
*/
public function testScaleEffect(): void {
// @todo Test also image upscaling in #3040887.
// @see https://www.drupal.org/project/drupal/issues/3040887
$this->assertImageEffect(['scale'], 'image_scale', [
'width' => 10,
'height' => 10,
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// Width was passed correctly.
$this->assertEquals(10, $calls['scale'][0][0]);
// Height was based off aspect ratio and passed correctly.
$this->assertEquals(10, $calls['scale'][0][1]);
}
/**
* Tests the 'image_crop' effect.
*/
public function testCropEffect(): void {
// @todo Test also keyword offsets in #3040887.
// @see https://www.drupal.org/project/drupal/issues/3040887
$this->assertImageEffect(['crop'], 'image_crop', [
'anchor' => 'top-1',
'width' => 3,
'height' => 4,
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// X was passed correctly.
$this->assertEquals(0, $calls['crop'][0][0]);
// Y was passed correctly.
$this->assertEquals(1, $calls['crop'][0][1]);
// Width was passed correctly.
$this->assertEquals(3, $calls['crop'][0][2]);
// Height was passed correctly.
$this->assertEquals(4, $calls['crop'][0][3]);
}
/**
* Tests the 'image_convert' effect.
*/
public function testConvertEffect(): void {
// Test jpeg.
$this->assertImageEffect(['convert'], 'image_convert', [
'extension' => 'jpeg',
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// Extension was passed correctly.
$this->assertEquals('jpeg', $calls['convert'][0][0]);
}
/**
* Tests the 'image_scale_and_crop' effect.
*/
public function testScaleAndCropEffect(): void {
$this->assertImageEffect(['scale_and_crop'], 'image_scale_and_crop', [
'width' => 5,
'height' => 10,
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// X was computed and passed correctly.
$this->assertEquals(7.5, $calls['scale_and_crop'][0][0]);
// Y was computed and passed correctly.
$this->assertEquals(0, $calls['scale_and_crop'][0][1]);
// Width was computed and passed correctly.
$this->assertEquals(5, $calls['scale_and_crop'][0][2]);
// Height was computed and passed correctly.
$this->assertEquals(10, $calls['scale_and_crop'][0][3]);
}
/**
* Tests the 'image_scale_and_crop' effect with an anchor.
*/
public function testScaleAndCropEffectWithAnchor(): void {
$this->assertImageEffect(['scale_and_crop'], 'image_scale_and_crop', [
'anchor' => 'top-1',
'width' => 5,
'height' => 10,
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// X was computed and passed correctly.
$this->assertEquals(0, $calls['scale_and_crop'][0][0]);
// Y was computed and passed correctly.
$this->assertEquals(1, $calls['scale_and_crop'][0][1]);
// Width was computed and passed correctly.
$this->assertEquals(5, $calls['scale_and_crop'][0][2]);
// Height was computed and passed correctly.
$this->assertEquals(10, $calls['scale_and_crop'][0][3]);
}
/**
* Tests the 'image_desaturate' effect.
*/
public function testDesaturateEffect(): void {
$this->assertImageEffect(['desaturate'], 'image_desaturate', []);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// No parameters were passed.
$this->assertEmpty($calls['desaturate'][0]);
}
/**
* Tests the image_rotate_effect() function.
*/
public function testRotateEffect(): void {
// @todo Test also with 'random' === TRUE in #3040887.
// @see https://www.drupal.org/project/drupal/issues/3040887
$this->assertImageEffect(['rotate'], 'image_rotate', [
'degrees' => 90,
'bgcolor' => '#fff',
]);
// Check the parameters.
$calls = $this->imageTestGetAllCalls();
// Degrees were passed correctly.
$this->assertEquals(90, $calls['rotate'][0][0]);
// Background color was passed correctly.
$this->assertEquals('#fff', $calls['rotate'][0][1]);
}
/**
* Tests image effect caching.
*/
public function testImageEffectsCaching(): void {
$state = $this->container->get('state');
// The 'image_module_test.counter' state variable value is incremented in
// image_module_test_image_effect_info_alter() every time the image effect
// plugin definitions are recomputed.
// @see image_module_test_image_effect_info_alter()
$state->set('image_module_test.counter', 0);
// First call should grab a fresh copy of the data.
$effects = $this->imageEffectPluginManager->getDefinitions();
$this->assertEquals(1, $state->get('image_module_test.counter'));
// Second call should come from cache.
$state->set('image_module_test.counter', 0);
$cached_effects = $this->imageEffectPluginManager->getDefinitions();
$this->assertEquals(0, $state->get('image_module_test.counter'));
// Check that cached effects are the same as the processed.
$this->assertSame($effects, $cached_effects);
}
/**
* Tests that validation errors are passed from the plugin to the parent form.
*/
public function testEffectFormValidationErrors(): void {
$form_builder = $this->container->get('form_builder');
/** @var \Drupal\image\ImageStyleInterface $image_style */
$image_style = ImageStyle::create([
'name' => 'foo',
'label' => 'Foo',
]);
$effect_id = $image_style->addImageEffect(['id' => 'image_scale']);
$image_style->save();
$form = new ImageEffectEditForm();
$form_state = (new FormState())->setValues([
'data' => ['width' => '', 'height' => ''],
]);
$form_builder->submitForm($form, $form_state, $image_style, $effect_id);
$errors = $form_state->getErrors();
$this->assertCount(1, $errors);
$error = reset($errors);
$this->assertEquals('Width and height can not both be blank.', $error);
}
}

View File

@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Provides a helper method for creating Image fields.
*/
trait ImageFieldCreationTrait {
/**
* Create a new image field.
*
* @param string $field_name
* The name of the new field (all lowercase). The Field UI 'field_' prefix
* is not added to the field name.
* @param string $entity_type
* The entity type that this field will be added to.
* For backwards-compatibility, a bundle is also accepted in this parameter.
* @param string $bundle
* The bundle this field will be added to.
* @param array $storage_settings
* (optional) A list of field storage settings that will be added to the
* defaults.
* @param array $field_settings
* (optional) A list of instance settings that will be added to the instance
* defaults.
* @param array $widget_settings
* (optional) Widget settings to be added to the widget defaults.
* @param array $formatter_settings
* (optional) Formatter settings to be added to the formatter defaults.
* @param string $description
* (optional) A description for the field. Defaults to ''.
*/
protected function createImageField($field_name, $entity_type, $bundle = '', $storage_settings = [], $field_settings = [], $widget_settings = [], $formatter_settings = [], $description = '') {
// Previously, nodes were the only entity type supported, For backwards
// compatibility, the $entity_type parameter is used as the $bundle in
// cases where only one machine name is passed.
if (func_num_args() == 2) {
@trigger_error('Calling ' . __METHOD__ . '() with only two arguments is deprecated in drupal:10.3.0 and three arguments will be required in drupal:11.0.0. See https://www.drupal.org/node/3441322', E_USER_DEPRECATED);
$bundle = $entity_type;
$entity_type = 'node';
}
elseif (is_array($bundle)) {
@trigger_error('Calling ' . __METHOD__ . '() without the $entity_type argument is deprecated in drupal:10.3.0 and this argument will be required in drupal:11.0.0. See https://www.drupal.org/node/3441322', E_USER_DEPRECATED);
return $this->createImageField($field_name, 'node', $entity_type, $bundle, $storage_settings, $field_settings, $widget_settings, $formatter_settings, $description);
}
FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $entity_type,
'type' => 'image',
'settings' => $storage_settings,
'cardinality' => !empty($storage_settings['cardinality']) ? $storage_settings['cardinality'] : 1,
])->save();
$field_config = FieldConfig::create([
'field_name' => $field_name,
'label' => $field_name,
'entity_type' => $entity_type,
'bundle' => $bundle,
'required' => !empty($field_settings['required']),
'settings' => $field_settings,
'description' => $description,
]);
$field_config->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay($entity_type, $bundle)
->setComponent($field_name, [
'type' => 'image_image',
'settings' => $widget_settings,
])
->save();
$display_repository->getViewDisplay($entity_type, $bundle)
->setComponent($field_name, [
'type' => 'image',
'settings' => $formatter_settings,
])
->save();
return $field_config;
}
}

View File

@@ -0,0 +1,219 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
/**
* Tests the image field rendering using entity fields of the image field type.
*
* @group image
*/
class ImageFormatterTest extends FieldKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['file', 'image'];
/**
* @var string
*/
protected $entityType;
/**
* @var string
*/
protected $bundle;
/**
* @var string
*/
protected $fieldName;
/**
* @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface
*/
protected $display;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installConfig(['field']);
$this->installEntitySchema('entity_test');
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
$this->entityType = 'entity_test';
$this->bundle = $this->entityType;
$this->fieldName = $this->randomMachineName();
FieldStorageConfig::create([
'entity_type' => $this->entityType,
'field_name' => $this->fieldName,
'type' => 'image',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'entity_type' => $this->entityType,
'field_name' => $this->fieldName,
'bundle' => $this->bundle,
'settings' => [
'file_extensions' => 'jpg',
],
])->save();
$this->display = \Drupal::service('entity_display.repository')
->getViewDisplay($this->entityType, $this->bundle)
->setComponent($this->fieldName, [
'type' => 'image',
'label' => 'hidden',
]);
$this->display->save();
}
/**
* Tests the cache tags from image formatters.
*/
public function testImageFormatterCacheTags(): void {
// Create a test entity with the image field set.
$entity = EntityTest::create([
'name' => $this->randomMachineName(),
]);
$entity->{$this->fieldName}->generateSampleItems(2);
$entity->save();
// Generate the render array to verify if the cache tags are as expected.
$build = $this->display->build($entity);
$this->assertEquals($entity->{$this->fieldName}[0]->entity->getCacheTags(), $build[$this->fieldName][0]['#cache']['tags'], 'First image cache tags is as expected');
$this->assertEquals($entity->{$this->fieldName}[1]->entity->getCacheTags(), $build[$this->fieldName][1]['#cache']['tags'], 'Second image cache tags is as expected');
}
/**
* Tests ImageFormatter's handling of SVG images.
*
* @requires extension gd
*/
public function testImageFormatterSvg(): void {
// Install the default image styles.
$this->installConfig(['image']);
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$png = File::create([
'uri' => 'public://test-image.png',
]);
$png->save();
// We need to create an actual empty PNG, or the GD toolkit will not
// consider the image valid.
$png_resource = imagecreate(300, 300);
imagefill($png_resource, 0, 0, imagecolorallocate($png_resource, 0, 0, 0));
imagepng($png_resource, $png->getFileUri());
$svg = File::create([
'uri' => 'public://test-image.svg',
]);
$svg->save();
// We don't have to put any real SVG data in here, because the GD toolkit
// won't be able to load it anyway.
touch($svg->getFileUri());
$entity = EntityTest::create([
'name' => $this->randomMachineName(),
$this->fieldName => [$png, $svg],
]);
$entity->save();
// Ensure that the display is using the medium image style.
$component = $this->display->getComponent($this->fieldName);
$component['settings']['image_style'] = 'medium';
$this->display->setComponent($this->fieldName, $component)->save();
$build = $this->display->build($entity);
// The first image is a PNG, so it is supported by the GD image toolkit.
// The image style should be applied with its cache tags, image derivative
// computed with its URI and dimensions.
$this->assertCacheTags($build[$this->fieldName][0], ImageStyle::load('medium')->getCacheTags());
$renderer->renderRoot($build[$this->fieldName][0]);
$this->assertEquals('medium', $build[$this->fieldName][0]['#image_style']);
// We check that the image URL contains the expected style directory
// structure.
$this->assertStringContainsString('styles/medium/public/test-image.png', (string) $build[$this->fieldName][0]['#markup']);
$this->assertStringContainsString('width="220"', (string) $build[$this->fieldName][0]['#markup']);
$this->assertStringContainsString('height="220"', (string) $build[$this->fieldName][0]['#markup']);
// The second image is an SVG, which is not supported by the GD toolkit.
// The image style should still be applied with its cache tags, but image
// derivative will not be available so <img> tag will point to the original
// image.
$this->assertCacheTags($build[$this->fieldName][1], ImageStyle::load('medium')->getCacheTags());
$renderer->renderRoot($build[$this->fieldName][1]);
$this->assertEquals('medium', $build[$this->fieldName][1]['#image_style']);
// We check that the image URL does not contain the style directory
// structure.
$this->assertStringNotContainsString('styles/medium/public/test-image.svg', (string) $build[$this->fieldName][1]['#markup']);
// Since we did not store original image dimensions, width and height
// HTML attributes will not be present.
$this->assertStringNotContainsString('width', (string) $build[$this->fieldName][1]['#markup']);
$this->assertStringNotContainsString('height', (string) $build[$this->fieldName][1]['#markup']);
}
/**
* Tests Image Formatter URL options handling.
*/
public function testImageFormatterUrlOptions(): void {
$this->display->setComponent($this->fieldName, ['settings' => ['image_link' => 'content']]);
// Create a test entity with the image field set.
$entity = EntityTest::create([
'name' => $this->randomMachineName(),
]);
$entity->{$this->fieldName}->generateSampleItems(2);
$entity->save();
// Generate the render array to verify URL options are as expected.
$build = $this->display->build($entity);
$this->assertInstanceOf(Url::class, $build[$this->fieldName][0]['#url']);
$build[$this->fieldName][0]['#url']->setOption('attributes', ['data-attributes-test' => 'test123']);
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$output = $renderer->renderRoot($build[$this->fieldName][0]);
$this->assertStringContainsString('<a href="' . $entity->toUrl()->toString() . '" data-attributes-test="test123"', (string) $output);
}
/**
* Asserts that a renderable array has a set of cache tags.
*
* @param array $renderable
* The renderable array. Must have a #cache[tags] element.
* @param array $cache_tags
* The expected cache tags.
*
* @internal
*/
protected function assertCacheTags(array $renderable, array $cache_tags): void {
$diff = array_diff($cache_tags, $renderable['#cache']['tags']);
$this->assertEmpty($diff);
}
}

View File

@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests config import for Image styles.
*
* @group image
*/
class ImageImportTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['system', 'image', 'image_module_test'];
/**
* Tests importing image styles.
*/
public function testImport(): void {
$style = ImageStyle::create([
'name' => 'test',
'label' => 'Test',
]);
$style->addImageEffect(['id' => 'image_module_test_null']);
$style->addImageEffect(['id' => 'image_module_test_null']);
$style->save();
$this->assertCount(2, $style->getEffects());
$uuid = \Drupal::service('uuid')->generate();
$style->set('effects', [
$uuid => [
'id' => 'image_module_test_null',
],
]);
$style->save();
$style = ImageStyle::load('test');
$this->assertCount(1, $style->getEffects());
}
}

View File

@@ -0,0 +1,203 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Database\Database;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\user\Entity\Role;
/**
* Tests using entity fields of the image field type.
*
* @group image
*/
class ImageItemTest extends FieldKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['file', 'image'];
/**
* Created file entity.
*
* @var \Drupal\file\Entity\File
*/
protected $image;
/**
* @var \Drupal\Core\Image\ImageFactory
*/
protected $imageFactory;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installConfig(['user']);
// Give anonymous users permission to access content, so that we can view
// and download public file.
$anonymous_role = Role::load(Role::ANONYMOUS_ID);
$anonymous_role->grantPermission('access content');
$anonymous_role->save();
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test',
'type' => 'image',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test_generation',
'type' => 'image',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test',
'bundle' => 'entity_test',
'settings' => [
'file_extensions' => 'jpg',
],
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test_generation',
'bundle' => 'entity_test',
'settings' => [
'min_resolution' => '800x800',
],
])->save();
\Drupal::service('file_system')->copy($this->root . '/core/misc/druplicon.png', 'public://example.jpg');
$this->image = File::create([
'uri' => 'public://example.jpg',
]);
$this->image->save();
$this->imageFactory = $this->container->get('image.factory');
}
/**
* Tests using entity fields of the image field type.
*/
public function testImageItem(): void {
// Create a test entity with the image field set.
$entity = EntityTest::create();
$entity->image_test->target_id = $this->image->id();
$entity->image_test->alt = $alt = $this->randomMachineName();
$entity->image_test->title = $title = $this->randomMachineName();
$entity->name->value = $this->randomMachineName();
$entity->save();
$entity = EntityTest::load($entity->id());
$this->assertInstanceOf(FieldItemListInterface::class, $entity->image_test);
$this->assertInstanceOf(FieldItemInterface::class, $entity->image_test[0]);
$this->assertEquals($this->image->id(), $entity->image_test->target_id);
$this->assertEquals($alt, $entity->image_test->alt);
$this->assertEquals($title, $entity->image_test->title);
$image = $this->imageFactory->get('public://example.jpg');
$this->assertEquals($image->getWidth(), $entity->image_test->width);
$this->assertEquals($image->getHeight(), $entity->image_test->height);
$this->assertEquals($this->image->id(), $entity->image_test->entity->id());
$this->assertEquals($this->image->uuid(), $entity->image_test->entity->uuid());
// Make sure the computed entity reflects updates to the referenced file.
\Drupal::service('file_system')->copy($this->root . '/core/misc/druplicon.png', 'public://example-2.jpg');
$image2 = File::create([
'uri' => 'public://example-2.jpg',
]);
$image2->save();
$entity->image_test->target_id = $image2->id();
$entity->image_test->alt = $new_alt = $this->randomMachineName();
// The width and height is only updated when width is not set.
$entity->image_test->width = NULL;
$entity->save();
$this->assertEquals($image2->id(), $entity->image_test->entity->id());
$this->assertEquals($image2->getFileUri(), $entity->image_test->entity->getFileUri());
$image = $this->imageFactory->get('public://example-2.jpg');
$this->assertEquals($image->getWidth(), $entity->image_test->width);
$this->assertEquals($image->getHeight(), $entity->image_test->height);
$this->assertEquals($new_alt, $entity->image_test->alt);
// Check that the image item can be set to the referenced file directly.
$entity->image_test = $this->image;
$this->assertEquals($this->image->id(), $entity->image_test->target_id);
// Delete the image and try to save the entity again.
$this->image->delete();
$entity = EntityTest::create(['name' => $this->randomMachineName()]);
$entity->save();
// Test image item properties.
$expected = ['target_id', 'entity', 'alt', 'title', 'width', 'height'];
$properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
$this->assertEquals($expected, array_keys($properties));
}
/**
* Tests generateSampleItems() method under different dimensions.
*/
public function testImageItemSampleValueGeneration(): void {
// Default behavior. No dimensions configuration.
$entity = EntityTest::create();
$entity->image_test->generateSampleItems();
$this->entityValidateAndSave($entity);
$this->assertEquals('image/jpeg', $entity->image_test->entity->get('filemime')->value);
// Max dimensions bigger than 600x600.
$entity->image_test_generation->generateSampleItems();
$this->entityValidateAndSave($entity);
$imageItem = $entity->image_test_generation->first()->getValue();
$this->assertEquals('800', $imageItem['width']);
$this->assertEquals('800', $imageItem['height']);
}
/**
* Tests a malformed image.
*/
public function testImageItemMalformed(): void {
\Drupal::service('module_installer')->install(['dblog']);
// Validate entity is an image and don't gather dimensions if it is not.
$entity = EntityTest::create();
$entity->image_test = NULL;
$entity->image_test->target_id = 9999;
$entity->save();
// Check that the proper warning has been logged.
$arguments = [
'%id' => 9999,
];
$logged = Database::getConnection()->select('watchdog')
->fields('watchdog', ['variables'])
->condition('type', 'image')
->condition('message', "Missing file with ID %id.")
->execute()
->fetchField();
$this->assertEquals(serialize($arguments), $logged);
$this->assertEmpty($entity->image_test->width);
$this->assertEmpty($entity->image_test->height);
}
}

View File

@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\StreamWrapper\PrivateStream;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\StreamWrapper\StreamWrapperManager;
use Drupal\file_test\StreamWrapper\DummyReadOnlyStreamWrapper;
use Drupal\file_test\StreamWrapper\DummyRemoteReadOnlyStreamWrapper;
use Drupal\file_test\StreamWrapper\DummyStreamWrapper;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests derivative generation with source images using stream wrappers.
*
* @group image
*/
class ImageStyleCustomStreamWrappersTest extends KernelTestBase {
/**
* Modules to enable.
*
* @var string[]
*/
protected static $modules = ['system', 'image'];
/**
* A testing image style entity.
*
* @var \Drupal\image\ImageStyleInterface
*/
protected $imageStyle;
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->fileSystem = $this->container->get('file_system');
$this->config('system.file')->set('default_scheme', 'public')->save();
$this->imageStyle = ImageStyle::create([
'name' => 'test',
'label' => 'Test',
]);
$this->imageStyle->save();
}
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
parent::register($container);
foreach ($this->providerTestCustomStreamWrappers() as $stream_wrapper) {
$scheme = $stream_wrapper[0];
$class = $stream_wrapper[2];
$container->register("stream_wrapper.$scheme", $class)
->addTag('stream_wrapper', ['scheme' => $scheme]);
}
}
/**
* Tests derivative creation with several source on a local writable stream.
*
* @dataProvider providerTestCustomStreamWrappers
*
* @param string $source_scheme
* The source stream wrapper scheme.
* @param string $expected_scheme
* The derivative expected stream wrapper scheme.
*/
public function testCustomStreamWrappers($source_scheme, $expected_scheme): void {
$derivative_uri = $this->imageStyle->buildUri("$source_scheme://some/path/image.png");
$derivative_scheme = StreamWrapperManager::getScheme($derivative_uri);
// Check that the derivative scheme is the expected scheme.
$this->assertSame($expected_scheme, $derivative_scheme);
// Check that the derivative URI is the expected one.
$expected_uri = "$expected_scheme://styles/{$this->imageStyle->id()}/$source_scheme/some/path/image.png";
$this->assertSame($expected_uri, $derivative_uri);
}
/**
* Provide test cases for testCustomStreamWrappers().
*
* Derivatives created from writable source stream wrappers will inherit the
* scheme from source. Derivatives created from read-only stream wrappers will
* fall-back to the default scheme.
*
* @return array[]
* An array having each element an array with three items:
* - The source stream wrapper scheme.
* - The derivative expected stream wrapper scheme.
* - The stream wrapper service class.
*/
public static function providerTestCustomStreamWrappers() {
return [
['public', 'public', PublicStream::class],
['private', 'private', PrivateStream::class],
['dummy', 'dummy', DummyStreamWrapper::class],
['dummy-readonly', 'public', DummyReadOnlyStreamWrapper::class],
['dummy-remote-readonly', 'public', DummyRemoteReadOnlyStreamWrapper::class],
];
}
}

View File

@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\KernelTestBase;
use Drupal\node\Entity\NodeType;
/**
* Tests the integration of ImageStyle with the core.
*
* @group image
*/
class ImageStyleIntegrationTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'image',
'file',
'field',
'system',
'user',
'node',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('node');
}
/**
* Tests the dependency between ImageStyle and entity display components.
*/
public function testEntityDisplayDependency(): void {
// Create two image styles.
/** @var \Drupal\image\ImageStyleInterface $style */
$style = ImageStyle::create([
'name' => 'main_style',
'label' => 'Main',
]);
$style->save();
/** @var \Drupal\image\ImageStyleInterface $replacement */
$replacement = ImageStyle::create([
'name' => 'replacement_style',
'label' => 'Replacement',
]);
$replacement->save();
NodeType::create([
'type' => 'note',
'name' => 'Note',
])->save();
// Create an image field and attach it to the 'note' node-type.
FieldStorageConfig::create([
'entity_type' => 'node',
'field_name' => 'sticker',
'type' => 'image',
])->save();
FieldConfig::create([
'entity_type' => 'node',
'field_name' => 'sticker',
'bundle' => 'note',
])->save();
// Create the default entity view display and set the 'sticker' field to use
// the 'main_style' images style in formatter.
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
$view_display = EntityViewDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'note',
'mode' => 'default',
'status' => TRUE,
])->setComponent('sticker', ['settings' => ['image_style' => 'main_style']]);
$view_display->save();
// Create the default entity form display and set the 'sticker' field to use
// the 'main_style' images style in the widget.
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = EntityFormDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'note',
'mode' => 'default',
'status' => TRUE,
])->setComponent('sticker', ['settings' => ['preview_image_style' => 'main_style']]);
$form_display->save();
// Check that the entity displays exists before dependency removal.
$this->assertNotNull(EntityViewDisplay::load($view_display->id()));
$this->assertNotNull(EntityFormDisplay::load($form_display->id()));
// Delete the 'main_style' image style. Before that, emulate the UI process
// of selecting a replacement style by setting the replacement image style
// ID in the image style storage.
/** @var \Drupal\image\ImageStyleStorageInterface $storage */
$storage = $this->container->get('entity_type.manager')->getStorage($style->getEntityTypeId());
$storage->setReplacementId('main_style', 'replacement_style');
$style->delete();
// Check that the entity displays exists after dependency removal.
$this->assertNotNull($view_display = EntityViewDisplay::load($view_display->id()));
$this->assertNotNull($form_display = EntityFormDisplay::load($form_display->id()));
// Check that the 'sticker' formatter component exists in both displays.
$this->assertNotNull($formatter = $view_display->getComponent('sticker'));
$this->assertNotNull($widget = $form_display->getComponent('sticker'));
// Check that both displays are using now 'replacement_style' for images.
$this->assertSame('replacement_style', $formatter['settings']['image_style']);
$this->assertSame('replacement_style', $widget['settings']['preview_image_style']);
// Delete the 'replacement_style' without setting a replacement image style.
$replacement->delete();
// The entity view and form displays exists after dependency removal.
$this->assertNotNull($view_display = EntityViewDisplay::load($view_display->id()));
$this->assertNotNull($form_display = EntityFormDisplay::load($form_display->id()));
// The 'sticker' formatter component should be hidden in view display.
$this->assertNull($view_display->getComponent('sticker'));
$this->assertTrue($view_display->get('hidden')['sticker']);
// The 'sticker' widget component should be active in form displays, but the
// image preview should be disabled.
$this->assertNotNull($widget = $form_display->getComponent('sticker'));
$this->assertSame('', $widget['settings']['preview_image_style']);
}
/**
* Tests renaming the ImageStyle.
*/
public function testEntityDisplayDependencyRename(): void {
// Create an image style.
/** @var \Drupal\image\ImageStyleInterface $style */
$style = ImageStyle::create([
'name' => 'main_style',
'label' => 'Main',
]);
$style->save();
NodeType::create([
'type' => 'note',
'name' => 'Note',
])->save();
// Create an image field and attach it to the 'note' node-type.
FieldStorageConfig::create([
'entity_type' => 'node',
'field_name' => 'sticker',
'type' => 'image',
])->save();
FieldConfig::create([
'entity_type' => 'node',
'field_name' => 'sticker',
'bundle' => 'note',
])->save();
// Create the default entity view display and set the 'sticker' field to use
// the 'main_style' images style in formatter.
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $view_display */
$view_display = EntityViewDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'note',
'mode' => 'default',
'status' => TRUE,
])->setComponent('sticker', ['settings' => ['image_style' => 'main_style']]);
$view_display->save();
// Create the default entity form display and set the 'sticker' field to use
// the 'main_style' images style in the widget.
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = EntityFormDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'note',
'mode' => 'default',
'status' => TRUE,
])->setComponent('sticker', ['settings' => ['preview_image_style' => 'main_style']]);
$form_display->save();
// Check that the entity displays exists before dependency renaming.
$this->assertNotNull(EntityViewDisplay::load($view_display->id()));
$this->assertNotNull(EntityFormDisplay::load($form_display->id()));
// Rename the 'main_style' image style.
$style->setName('main_style_renamed');
$style->save();
// Check that the entity displays exists after dependency renaming.
$this->assertNotNull($view_display = EntityViewDisplay::load($view_display->id()));
$this->assertNotNull($form_display = EntityFormDisplay::load($form_display->id()));
// Check that the 'sticker' formatter component exists in both displays.
$this->assertNotNull($formatter = $view_display->getComponent('sticker'));
$this->assertNotNull($widget = $form_display->getComponent('sticker'));
// Check that both displays are using now 'main_style_renamed' for images.
$this->assertSame('main_style_renamed', $formatter['settings']['image_style']);
$this->assertSame('main_style_renamed', $widget['settings']['preview_image_style']);
}
}

View File

@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\Core\Config\ConfigEntityValidationTestBase;
/**
* Tests validation of image_style entities.
*
* @group image
* @group #slow
*/
class ImageStyleValidationTest extends ConfigEntityValidationTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->entity = ImageStyle::create([
'name' => 'test',
'label' => 'Test',
]);
$this->entity->save();
}
}

View File

@@ -0,0 +1,245 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\File\FileExists;
use Drupal\Core\Url;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\image\Entity\ImageStyle;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\TestFileCreationTrait;
/**
* Tests image theme functions.
*
* @group image
*/
class ImageThemeFunctionTest extends KernelTestBase {
use TestFileCreationTrait {
getTestFiles as drupalGetTestFiles;
compareFiles as drupalCompareFiles;
}
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'entity_test',
'field',
'file',
'image',
'system',
'user',
];
/**
* Created file entity.
*
* @var \Drupal\file\Entity\File
*/
protected $image;
/**
* @var \Drupal\Core\Image\ImageFactory
*/
protected $imageFactory;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('entity_test');
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
$this->installEntitySchema('user');
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test',
'type' => 'image',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'image_test',
'bundle' => 'entity_test',
])->save();
\Drupal::service('file_system')->copy($this->root . '/core/misc/druplicon.png', 'public://example.jpg');
$this->image = File::create([
'uri' => 'public://example.jpg',
]);
$this->image->save();
$this->imageFactory = $this->container->get('image.factory');
}
/**
* Tests usage of the image field formatters.
*/
public function testImageFormatterTheme(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
// Create an image.
$files = $this->drupalGetTestFiles('image');
$file = reset($files);
$original_uri = \Drupal::service('file_system')->copy($file->uri, 'public://', FileExists::Rename);
// Create a style.
$style = ImageStyle::create(['name' => 'test', 'label' => 'Test']);
$style->save();
$url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));
// Create a test entity with the image field set.
$entity = EntityTest::create();
$entity->image_test->target_id = $this->image->id();
$entity->image_test->alt = NULL;
$entity->image_test->uri = $original_uri;
$image = $this->imageFactory->get('public://example.jpg');
$entity->save();
// Create the base element that we'll use in the tests below.
$path = $this->randomMachineName();
$base_element = [
'#theme' => 'image_formatter',
'#image_style' => 'test',
'#item' => $entity->image_test,
'#url' => Url::fromUri('base:' . $path),
];
// Test using theme_image_formatter() with a NULL value for the alt option.
$element = $base_element;
$this->setRawContent($renderer->renderRoot($element));
$elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
$this->assertCount(1, $elements, 'theme_image_formatter() correctly renders with a NULL value for the alt option.');
// Test using theme_image_formatter() without an image title, alt text, or
// link options.
$element = $base_element;
$element['#item']->alt = '';
$this->setRawContent($renderer->renderRoot($element));
$elements = $this->xpath('//a[@href=:path]/img[@src=:url and @width=:width and @height=:height and @alt=""]', [':path' => base_path() . $path, ':url' => $url, ':width' => $image->getWidth(), ':height' => $image->getHeight()]);
$this->assertCount(1, $elements, 'theme_image_formatter() correctly renders without title, alt, or path options.');
// Link the image to a fragment on the page, and not a full URL.
$fragment = $this->randomMachineName();
$element = $base_element;
$element['#url'] = Url::fromRoute('<none>', [], ['fragment' => $fragment]);
$this->setRawContent($renderer->renderRoot($element));
$elements = $this->xpath('//a[@href=:fragment]/img[@src=:url and @width=:width and @height=:height and @alt=""]', [
':fragment' => '#' . $fragment,
':url' => $url,
':width' => $image->getWidth(),
':height' => $image->getHeight(),
]);
$this->assertCount(1, $elements, 'theme_image_formatter() correctly renders a link fragment.');
}
/**
* Tests usage of the image style theme function.
*/
public function testImageStyleTheme(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
// Create an image.
$files = $this->drupalGetTestFiles('image');
$file = reset($files);
$original_uri = \Drupal::service('file_system')->copy($file->uri, 'public://', FileExists::Rename);
// Create a style.
$style = ImageStyle::create(['name' => 'image_test', 'label' => 'Test']);
$style->save();
$url = \Drupal::service('file_url_generator')->transformRelative($style->buildUrl($original_uri));
// Create the base element that we'll use in the tests below.
$base_element = [
'#theme' => 'image_style',
'#style_name' => 'image_test',
'#uri' => $original_uri,
];
$element = $base_element;
$this->setRawContent($renderer->renderRoot($element));
$elements = $this->xpath('//img[@src=:url and @alt=""]', [':url' => $url]);
$this->assertCount(1, $elements, 'theme_image_style() renders an image correctly.');
// Test using theme_image_style() with a NULL value for the alt option.
$element = $base_element;
$element['#alt'] = NULL;
$this->setRawContent($renderer->renderRoot($element));
$elements = $this->xpath('//img[@src=:url]', [':url' => $url]);
$this->assertCount(1, $elements, 'theme_image_style() renders an image correctly with a NULL value for the alt option.');
}
/**
* Tests image alt attribute functionality.
*/
public function testImageAltFunctionality(): void {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
// Test using alt directly with alt attribute.
$image_with_alt_property = [
'#theme' => 'image',
'#uri' => '/core/themes/olivero/logo.svg',
'#alt' => 'Regular alt',
'#title' => 'Test title',
'#width' => '50%',
'#height' => '50%',
'#attributes' => ['class' => 'image-with-regular-alt', 'id' => 'my-img'],
];
$this->setRawContent($renderer->renderRoot($image_with_alt_property));
$elements = $this->xpath('//img[contains(@class, class) and contains(@alt, :alt)]', [":class" => "image-with-regular-alt", ":alt" => "Regular alt"]);
$this->assertCount(1, $elements, 'Regular alt displays correctly');
// Test using alt attribute inside attributes.
$image_with_alt_attribute_alt_attribute = [
'#theme' => 'image',
'#uri' => '/core/themes/olivero/logo.svg',
'#width' => '50%',
'#height' => '50%',
'#attributes' => [
'class' => 'image-with-attribute-alt',
'id' => 'my-img',
'title' => 'New test title',
'alt' => 'Attribute alt',
],
];
$this->setRawContent($renderer->renderRoot($image_with_alt_attribute_alt_attribute));
$elements = $this->xpath('//img[contains(@class, class) and contains(@alt, :alt)]', [":class" => "image-with-attribute-alt", ":alt" => "Attribute alt"]);
$this->assertCount(1, $elements, 'Attribute alt displays correctly');
// Test using alt attribute as property and inside attributes.
$image_with_alt_attribute_both = [
'#theme' => 'image',
'#uri' => '/core/themes/olivero/logo.svg',
'#width' => '50%',
'#height' => '50%',
'#alt' => 'Kitten sustainable',
'#attributes' => [
'class' => 'image-with-attribute-alt',
'id' => 'my-img',
'title' => 'New test title',
'alt' => 'Attribute alt',
],
];
$this->setRawContent($renderer->renderRoot($image_with_alt_attribute_both));
$elements = $this->xpath('//img[contains(@class, class) and contains(@alt, :alt)]', [":class" => "image-with-attribute-alt", ":alt" => "Attribute alt"]);
$this->assertCount(1, $elements, 'Attribute alt overrides alt property if both set.');
}
}

View File

@@ -0,0 +1,170 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Migrate\d6;
use Drupal\Core\Database\Database;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\ImageEffectPluginCollection;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Exception\RequirementsException;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
* Tests migration of ImageCache presets to image styles.
*
* @group image
*/
class MigrateImageCacheTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installConfig(['image']);
}
/**
* Tests that an exception is thrown when ImageCache is not installed.
*/
public function testMissingTable(): void {
$this->sourceDatabase->update('system')
->fields([
'status' => 0,
])
->condition('name', 'imagecache')
->condition('type', 'module')
->execute();
$this->expectException(RequirementsException::class);
$this->getMigration('d6_imagecache_presets')
->getSourcePlugin()
->checkRequirements();
}
/**
* Tests basic passing migrations.
*/
public function testPassingMigration(): void {
$this->executeMigration('d6_imagecache_presets');
/** @var \Drupal\image\Entity\ImageStyle $style */
$style = ImageStyle::load('big_blue_cheese');
// Check basic Style info.
$this->assertSame('big_blue_cheese', $style->get('name'), 'ImageStyle name set correctly');
$this->assertSame('big_blue_cheese', $style->get('label'), 'ImageStyle label set correctly');
// Test effects.
$effects = $style->getEffects();
// Check crop effect.
$this->assertImageEffect($effects, 'image_crop', [
'width' => 555,
'height' => 5555,
'anchor' => 'center-center',
]);
// Check resize effect.
$this->assertImageEffect($effects, 'image_resize', [
'width' => 55,
'height' => 55,
]);
// Check rotate effect.
$this->assertImageEffect($effects, 'image_rotate', [
'degrees' => 55,
'random' => FALSE,
'bgcolor' => '',
]);
}
/**
* Tests that missing actions causes failures.
*/
public function testMissingEffectPlugin(): void {
Database::getConnection('default', 'migrate')->insert("imagecache_action")
->fields([
'presetid',
'weight',
'module',
'action',
'data',
])
->values([
'presetid' => '1',
'weight' => '0',
'module' => 'imagecache',
'action' => 'imagecache_deprecated_scale',
'data' => 'a:3:{s:3:"fit";s:7:"outside";s:5:"width";s:3:"200";s:6:"height";s:3:"200";}',
])->execute();
$this->startCollectingMessages();
$this->executeMigration('d6_imagecache_presets');
$messages = iterator_to_array($this->migration->getIdMap()->getMessages());
$this->assertCount(1, $messages);
$this->assertStringContainsString('The "image_deprecated_scale" plugin does not exist.', $messages[0]->message);
$this->assertEquals(MigrationInterface::MESSAGE_ERROR, $messages[0]->level);
}
/**
* Tests that missing action's causes failures.
*/
public function testInvalidCropValues(): void {
Database::getConnection('default', 'migrate')->insert("imagecache_action")
->fields([
'presetid',
'weight',
'module',
'action',
'data',
])
->values([
'presetid' => '1',
'weight' => '0',
'module' => 'imagecache',
'action' => 'imagecache_crop',
'data' => serialize([
'xoffset' => '10',
'yoffset' => '10',
]),
])->execute();
$this->startCollectingMessages();
$this->executeMigration('d6_imagecache_presets');
$this->assertEquals([
'error' => [
'The Drupal 8 image crop effect does not support numeric values for x and y offsets. Use keywords to set crop effect offsets instead.',
],
], $this->migrateMessages);
}
/**
* Assert that a given image effect is migrated.
*
* @param \Drupal\image\ImageEffectPluginCollection $collection
* Collection of effects
* @param string $id
* Id that should exist in the collection.
* @param array $config
* Expected configuration for the collection.
*
* @internal
*/
protected function assertImageEffect(ImageEffectPluginCollection $collection, string $id, array $config): void {
/** @var \Drupal\image\ConfigurableImageEffectBase $effect */
foreach ($collection as $effect) {
$effect_config = $effect->getConfiguration();
if ($effect_config['id'] == $id && $effect_config['data'] == $config) {
// We found this effect so the assertion is successful.
return;
}
}
// The loop did not find the effect so we it was not imported correctly.
$this->fail('Effect ' . $id . ' did not import correctly');
}
}

View File

@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Migrate\d6;
use Drupal\node\Entity\Node;
use Drupal\Tests\node\Kernel\Migrate\d6\MigrateNodeTestBase;
use Drupal\Tests\file\Kernel\Migrate\d6\FileMigrationTestTrait;
/**
* Image migration test.
*
* This extends the node test, because the D6 fixture has images; they just
* need to be migrated into D8.
*
* @group migrate_drupal_6
*/
class MigrateImageTest extends MigrateNodeTestBase {
use FileMigrationTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['menu_ui'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->setUpMigratedFiles();
$this->installSchema('file', ['file_usage']);
$this->executeMigrations([
'd6_node',
]);
}
/**
* Tests image migration from Drupal 6 to 8.
*/
public function testNode(): void {
$node = Node::load(9);
// Test the image field sub fields.
$this->assertSame('2', $node->field_test_imagefield->target_id);
$this->assertSame('Test alt', $node->field_test_imagefield->alt);
$this->assertSame('Test title', $node->field_test_imagefield->title);
$this->assertSame('80', $node->field_test_imagefield->width);
$this->assertSame('60', $node->field_test_imagefield->height);
}
}

View File

@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Migrate\d7;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Tests migration of Image variables to configuration.
*
* @group image
*/
class MigrateImageSettingsTest extends MigrateDrupal7TestBase {
protected static $modules = ['image'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->executeMigration('d7_image_settings');
}
/**
* Tests the migration.
*/
public function testMigration(): void {
$config = $this->config('image.settings');
// These settings are not recommended...
$this->assertTrue($config->get('allow_insecure_derivatives'));
$this->assertTrue($config->get('suppress_itok_output'));
$this->assertSame("core/misc/druplicon.png", $config->get('preview_image'));
}
}

View File

@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Migrate\d7;
use Drupal\image\Entity\ImageStyle;
use Drupal\image\ImageStyleInterface;
use Drupal\image\ImageEffectBase;
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
/**
* Test image styles migration to config entities.
*
* @group image
*/
class MigrateImageStylesTest extends MigrateDrupal7TestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installConfig(static::$modules);
$this->executeMigration('d7_image_styles');
}
/**
* Tests the image styles migration.
*/
public function testImageStylesMigration(): void {
$this->assertEntity('custom_image_style_1', "Custom image style 1", ['image_scale_and_crop', 'image_desaturate'], [['width' => 55, 'height' => 55, 'anchor' => 'center-center'], []]);
$this->assertEntity('custom_image_style_2', "Custom image style 2", ['image_resize', 'image_rotate'], [['width' => 55, 'height' => 100], ['degrees' => 45, 'bgcolor' => '#FFFFFF', 'random' => FALSE]]);
$this->assertEntity('custom_image_style_3', "Custom image style 3", ['image_scale', 'image_crop'], [['width' => 150, 'height' => NULL, 'upscale' => FALSE], ['width' => 50, 'height' => 50, 'anchor' => 'left-top']]);
}
/**
* Asserts various aspects of an ImageStyle entity.
*
* @param string $id
* The expected image style ID.
* @param string $label
* The expected image style label.
* @param array $expected_effect_plugins
* An array of expected plugins attached to the image style entity
* @param array $expected_effect_config
* An array of expected configuration for each effect in the image style
*/
protected function assertEntity(string $id, string $label, array $expected_effect_plugins, array $expected_effect_config): void {
$style = ImageStyle::load($id);
$this->assertInstanceOf(ImageStyleInterface::class, $style);
/** @var \Drupal\image\ImageStyleInterface $style */
$this->assertSame($id, $style->id());
$this->assertSame($label, $style->label());
// Check the number of effects associated with the style.
$effects = $style->getEffects();
$this->assertSameSize($expected_effect_plugins, $effects);
$index = 0;
foreach ($effects as $effect) {
$this->assertInstanceOf(ImageEffectBase::class, $effect);
$this->assertSame($expected_effect_plugins[$index], $effect->getPluginId());
$config = $effect->getConfiguration();
$this->assertSame($expected_effect_config[$index], $config['data']);
$index++;
}
}
}

View File

@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Plugin\migrate\source\d6;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
// cspell:ignore actionid imagecache presetid presetname
/**
* Tests the d6_imagecache_presets source plugin.
*
* @covers \Drupal\image\Plugin\migrate\source\d6\ImageCachePreset
*
* @group image
*/
class ImageCachePresetTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public static function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['imagecache_preset'] = [
[
'presetid' => '1',
'presetname' => 'slack_jaw_boys',
],
];
$tests[0]['source_data']['imagecache_action'] = [
[
'actionid' => '3',
'presetid' => '1',
'weight' => '0',
'module' => 'imagecache',
'action' => 'imagecache_scale_and_crop',
'data' => 'a:2:{s:5:"width";s:4:"100%";s:6:"height";s:4:"100%";}',
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'presetid' => '1',
'presetname' => 'slack_jaw_boys',
'actions' => [
[
'actionid' => '3',
'presetid' => '1',
'weight' => '0',
'module' => 'imagecache',
'action' => 'imagecache_scale_and_crop',
'data' => [
'width' => '100%',
'height' => '100%',
],
],
],
],
];
return $tests;
}
}

View File

@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Plugin\migrate\source\d7;
use Drupal\Tests\migrate\Kernel\MigrateSqlSourceTestBase;
// cspell:ignore ieid isid
/**
* Tests the D7 ImageStyles source plugin.
*
* @covers \Drupal\image\Plugin\migrate\source\d7\ImageStyles
*
* @group image
*/
class ImageStylesTest extends MigrateSqlSourceTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image', 'migrate_drupal'];
/**
* {@inheritdoc}
*/
public static function providerSource() {
$tests = [];
// The source data.
$tests[0]['source_data']['image_styles'] = [
[
'isid' => 1,
'name' => 'custom_image_style_1',
'label' => 'Custom image style 1',
],
];
$tests[0]['source_data']['image_effects'] = [
[
'ieid' => 1,
'isid' => 1,
'weight' => 1,
'name' => 'image_desaturate',
'data' => serialize([]),
],
];
// The expected results.
$tests[0]['expected_data'] = [
[
'isid' => 1,
'name' => 'custom_image_style_1',
'label' => 'Custom image style 1',
'effects' => [
[
'ieid' => 1,
'isid' => 1,
'weight' => 1,
'name' => 'image_desaturate',
'data' => [],
],
],
],
];
return $tests;
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel;
use Drupal\Core\Config\Schema\SchemaIncompleteException;
use Drupal\KernelTests\KernelTestBase;
/**
* @group image
*/
class SettingsConfigValidationTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['image'];
/**
* Tests that the preview_image setting must be an existing image file.
*/
public function testPreviewImagePathIsValidated(): void {
$this->installConfig('image');
// Drupal does not have a hard dependency on the fileinfo extension and
// implements an extension-based mimetype guesser. Therefore, we must use
// an incorrect extension here instead of writing text to a supposed PNG
// file and depending on a check of the file contents.
$file = sys_get_temp_dir() . '/fake_image.png.txt';
file_put_contents($file, 'Not an image!');
$this->expectException(SchemaIncompleteException::class);
$this->expectExceptionMessage('[preview_image] This file is not a valid image.');
$this->config('image.settings')
->set('preview_image', $file)
->save();
}
}

View File

@@ -0,0 +1,110 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Views;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\views\Views;
/**
* Tests image views data.
*
* @group image
*/
class ImageViewsDataTest extends ViewsKernelTestBase {
/**
* Modules to install.
*
* @var array
*/
protected static $modules = [
'image',
'file',
'views',
'entity_test',
'user',
'field',
];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE): void {
parent::setUp($import_test_views);
$this->installEntitySchema('entity_test');
$this->installEntitySchema('entity_test_mul');
}
/**
* Tests views data generated for image field relationship.
*
* @see image_field_views_data()
* @see image_field_views_data_views_data_alter()
*/
public function testRelationshipViewsData(): void {
// Create image field to entity_test.
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_base_image',
'type' => 'image',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_base_image',
'bundle' => 'entity_test',
])->save();
// Check the generated views data.
$views_data = Views::viewsData()->get('entity_test__field_base_image');
$relationship = $views_data['field_base_image_target_id']['relationship'];
$this->assertEquals('standard', $relationship['id']);
$this->assertEquals('file_managed', $relationship['base']);
$this->assertEquals('fid', $relationship['base field']);
$this->assertEquals('file', $relationship['entity type']);
// Check the backwards reference.
$views_data = Views::viewsData()->get('file_managed');
$relationship = $views_data['reverse_field_base_image_entity_test']['relationship'];
$this->assertEquals('entity_reverse', $relationship['id']);
$this->assertEquals('entity_test', $relationship['base']);
$this->assertEquals('id', $relationship['base field']);
$this->assertEquals('entity_test__field_base_image', $relationship['field table']);
$this->assertEquals('field_base_image_target_id', $relationship['field field']);
$this->assertEquals('field_base_image', $relationship['field_name']);
$this->assertEquals('entity_test', $relationship['entity_type']);
$this->assertEquals(['field' => 'deleted', 'value' => 0, 'numeric' => TRUE], $relationship['join_extra'][0]);
// Create image field to entity_test_mul.
FieldStorageConfig::create([
'entity_type' => 'entity_test_mul',
'field_name' => 'field_data_image',
'type' => 'image',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test_mul',
'field_name' => 'field_data_image',
'bundle' => 'entity_test_mul',
])->save();
// Check the generated views data.
$views_data = Views::viewsData()->get('entity_test_mul__field_data_image');
$relationship = $views_data['field_data_image_target_id']['relationship'];
$this->assertEquals('standard', $relationship['id']);
$this->assertEquals('file_managed', $relationship['base']);
$this->assertEquals('fid', $relationship['base field']);
$this->assertEquals('file', $relationship['entity type']);
// Check the backwards reference.
$views_data = Views::viewsData()->get('file_managed');
$relationship = $views_data['reverse_field_data_image_entity_test_mul']['relationship'];
$this->assertEquals('entity_reverse', $relationship['id']);
$this->assertEquals('entity_test_mul_property_data', $relationship['base']);
$this->assertEquals('id', $relationship['base field']);
$this->assertEquals('entity_test_mul__field_data_image', $relationship['field table']);
$this->assertEquals('field_data_image_target_id', $relationship['field field']);
$this->assertEquals('field_data_image', $relationship['field_name']);
$this->assertEquals('entity_test_mul', $relationship['entity_type']);
$this->assertEquals(['field' => 'deleted', 'value' => 0, 'numeric' => TRUE], $relationship['join_extra'][0]);
}
}

View File

@@ -0,0 +1,115 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Kernel\Views;
use Drupal\field\Entity\FieldConfig;
use Drupal\file\Entity\File;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\user\Entity\User;
use Drupal\views\Views;
use Drupal\views\Tests\ViewTestData;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests image on user relationship handler.
*
* @group image
*/
class RelationshipUserImageDataTest extends ViewsKernelTestBase {
/**
* Modules to install.
*
* @var array
*/
protected static $modules = [
'file',
'field',
'image',
'image_test_views',
'system',
'user',
];
/**
* Views used by this test.
*
* @var array
*/
public static $testViews = ['test_image_user_image_data'];
/**
* {@inheritdoc}
*/
protected function setUp($import_test_views = TRUE): void {
parent::setUp($import_test_views);
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
$this->installEntitySchema('user');
// Create the user profile field and instance.
FieldStorageConfig::create([
'entity_type' => 'user',
'field_name' => 'user_picture',
'type' => 'image',
'translatable' => '0',
])->save();
FieldConfig::create([
'label' => 'User Picture',
'description' => '',
'field_name' => 'user_picture',
'entity_type' => 'user',
'bundle' => 'user',
'required' => 0,
])->save();
ViewTestData::createTestViews(static::class, ['image_test_views']);
}
/**
* Tests using the views image relationship.
*/
public function testViewsHandlerRelationshipUserImageData(): void {
$file = File::create([
'fid' => 2,
'uid' => 2,
'filename' => 'image-test.jpg',
'uri' => "public://image-test.jpg",
'filemime' => 'image/jpeg',
'created' => 1,
'changed' => 1,
]);
$file->setPermanent();
$file->enforceIsNew();
file_put_contents($file->getFileUri(), file_get_contents('core/tests/fixtures/files/image-1.png'));
$file->save();
$account = User::create([
'name' => 'foo',
]);
$account->user_picture->target_id = 2;
$account->save();
$view = Views::getView('test_image_user_image_data');
// Tests \Drupal\taxonomy\Plugin\views\relationship\NodeTermData::calculateDependencies().
$expected = [
'module' => [
'file',
'user',
],
];
$this->assertSame($expected, $view->getDependencies());
$this->executeView($view);
$expected_result = [
[
'file_managed_user__user_picture_fid' => '2',
],
];
$column_map = ['file_managed_user__user_picture_fid' => 'file_managed_user__user_picture_fid'];
$this->assertIdenticalResultset($view, $expected_result, $column_map);
}
}

View File

@@ -0,0 +1,265 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Unit;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\image\Entity\ImageStyle
*
* @group Image
*/
class ImageStyleTest extends UnitTestCase {
/**
* The entity type used for testing.
*
* @var \Drupal\Core\Entity\EntityTypeInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $entityType;
/**
* The entity type manager used for testing.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $entityTypeManager;
/**
* The ID of the type of the entity under test.
*
* @var string
*/
protected $entityTypeId;
/**
* Gets a mocked image style for testing.
*
* @param string $image_effect_id
* The image effect ID.
* @param \Drupal\image\ImageEffectInterface|\PHPUnit\Framework\MockObject\MockObject $image_effect
* The image effect used for testing.
* @param array $stubs
* An array of additional method names to mock.
*
* @return \Drupal\image\ImageStyleInterface
* The mocked image style.
*/
protected function getImageStyleMock($image_effect_id, $image_effect, $stubs = []) {
$effectManager = $this->getMockBuilder('\Drupal\image\ImageEffectManager')
->disableOriginalConstructor()
->getMock();
$effectManager->expects($this->any())
->method('createInstance')
->with($image_effect_id)
->willReturn($image_effect);
$default_stubs = ['getImageEffectPluginManager', 'fileDefaultScheme'];
$image_style = $this->getMockBuilder('\Drupal\image\Entity\ImageStyle')
->setConstructorArgs([
['effects' => [$image_effect_id => ['id' => $image_effect_id]]],
$this->entityTypeId,
])
->onlyMethods(array_merge($default_stubs, $stubs))
->getMock();
$image_style->expects($this->any())
->method('getImageEffectPluginManager')
->willReturn($effectManager);
$image_style->expects($this->any())
->method('fileDefaultScheme')
->willReturnCallback([$this, 'fileDefaultScheme']);
return $image_style;
}
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->entityTypeId = $this->randomMachineName();
$provider = $this->randomMachineName();
$this->entityType = $this->createMock('\Drupal\Core\Entity\EntityTypeInterface');
$this->entityType->expects($this->any())
->method('getProvider')
->willReturn($provider);
$this->entityTypeManager = $this->createMock('\Drupal\Core\Entity\EntityTypeManagerInterface');
$this->entityTypeManager->expects($this->any())
->method('getDefinition')
->with($this->entityTypeId)
->willReturn($this->entityType);
}
/**
* @covers ::getDerivativeExtension
*/
public function testGetDerivativeExtension(): void {
$image_effect_id = $this->randomMachineName();
$logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
->setConstructorArgs([[], $image_effect_id, [], $logger])
->getMock();
$image_effect->expects($this->any())
->method('getDerivativeExtension')
->willReturn('png');
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
$extensions = ['jpeg', 'gif', 'png'];
foreach ($extensions as $extension) {
$extensionReturned = $image_style->getDerivativeExtension($extension);
$this->assertEquals('png', $extensionReturned);
}
}
/**
* @covers ::buildUri
*/
public function testBuildUri(): void {
// Image style that changes the extension.
$image_effect_id = $this->randomMachineName();
$logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
->setConstructorArgs([[], $image_effect_id, [], $logger])
->getMock();
$image_effect->expects($this->any())
->method('getDerivativeExtension')
->willReturn('png');
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
$this->assertEquals($image_style->buildUri('public://test.jpeg'), 'public://styles/' . $image_style->id() . '/public/test.jpeg.png');
// Image style that doesn't change the extension.
$image_effect_id = $this->randomMachineName();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
->setConstructorArgs([[], $image_effect_id, [], $logger])
->getMock();
$image_effect->expects($this->any())
->method('getDerivativeExtension')
->willReturnArgument(0);
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect);
$this->assertEquals($image_style->buildUri('public://test.jpeg'), 'public://styles/' . $image_style->id() . '/public/test.jpeg');
}
/**
* @covers ::getPathToken
*/
public function testGetPathToken(): void {
$logger = $this->getMockBuilder('\Psr\Log\LoggerInterface')->getMock();
$private_key = $this->randomMachineName();
$hash_salt = $this->randomMachineName();
// Image style that changes the extension.
$image_effect_id = $this->randomMachineName();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
->setConstructorArgs([[], $image_effect_id, [], $logger])
->getMock();
$image_effect->expects($this->any())
->method('getDerivativeExtension')
->willReturn('png');
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect, ['getPrivateKey', 'getHashSalt']);
$image_style->expects($this->any())
->method('getPrivateKey')
->willReturn($private_key);
$image_style->expects($this->any())
->method('getHashSalt')
->willReturn($hash_salt);
// Assert the extension has been added to the URI before creating the token.
$this->assertEquals($image_style->getPathToken('public://test.jpeg.png'), $image_style->getPathToken('public://test.jpeg'));
$this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg.png', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
$this->assertNotEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
// Image style that doesn't change the extension.
$image_effect_id = $this->randomMachineName();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase')
->setConstructorArgs([[], $image_effect_id, [], $logger])
->getMock();
$image_effect->expects($this->any())
->method('getDerivativeExtension')
->willReturnArgument(0);
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect, ['getPrivateKey', 'getHashSalt']);
$image_style->expects($this->any())
->method('getPrivateKey')
->willReturn($private_key);
$image_style->expects($this->any())
->method('getHashSalt')
->willReturn($hash_salt);
// Assert no extension has been added to the uri before creating the token.
$this->assertNotEquals($image_style->getPathToken('public://test.jpeg.png'), $image_style->getPathToken('public://test.jpeg'));
$this->assertNotEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg.png', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
$this->assertEquals(substr(Crypt::hmacBase64($image_style->id() . ':' . 'public://test.jpeg', $private_key . $hash_salt), 0, 8), $image_style->getPathToken('public://test.jpeg'));
}
/**
* @covers ::flush
*/
public function testFlush(): void {
$cache_tag_invalidator = $this->createMock('\Drupal\Core\Cache\CacheTagsInvalidator');
$file_system = $this->createMock('\Drupal\Core\File\FileSystemInterface');
$module_handler = $this->createMock('\Drupal\Core\Extension\ModuleHandlerInterface');
$stream_wrapper_manager = $this->createMock('\Drupal\Core\StreamWrapper\StreamWrapperManagerInterface');
$stream_wrapper_manager->expects($this->any())
->method('getWrappers')
->will($this->returnValue([]));
$theme_registry = $this->createMock('\Drupal\Core\Theme\Registry');
$container = new ContainerBuilder();
$container->set('cache_tags.invalidator', $cache_tag_invalidator);
$container->set('file_system', $file_system);
$container->set('module_handler', $module_handler);
$container->set('stream_wrapper_manager', $stream_wrapper_manager);
$container->set('theme.registry', $theme_registry);
\Drupal::setContainer($container);
$image_effect_id = $this->randomMachineName();
$image_effect = $this->getMockBuilder('\Drupal\image\ImageEffectBase');
$image_style = $this->getImageStyleMock($image_effect_id, $image_effect, ['buildUri', 'getCacheTagsToInvalidate']);
$image_style->expects($this->any())
->method('buildUri')
->willReturn('test.jpg');
$image_style->expects($this->any())
->method('getCacheTagsToInvalidate')
->willReturn([]);
// Assert the theme registry is reset.
$theme_registry
->expects($this->once())
->method('reset');
// Assert the cache tags are invalidated.
$cache_tag_invalidator
->expects($this->once())
->method('invalidateTags');
$image_style->flush();
// Assert the theme registry is not reset a path is flushed.
$theme_registry
->expects($this->never())
->method('reset');
// Assert the cache tags are not reset a path is flushed.
$cache_tag_invalidator
->expects($this->never())
->method('invalidateTags');
$image_style->flush('test.jpg');
}
/**
* Mock function for ImageStyle::fileDefaultScheme().
*/
public function fileDefaultScheme() {
return 'public';
}
}

View File

@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\image\Unit\PageCache;
use Drupal\Core\PageCache\ResponsePolicyInterface;
use Drupal\image\PageCache\DenyPrivateImageStyleDownload;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* @coversDefaultClass \Drupal\image\PageCache\DenyPrivateImageStyleDownload
* @group image
*/
class DenyPrivateImageStyleDownloadTest extends UnitTestCase {
/**
* The response policy under test.
*
* @var \Drupal\image\PageCache\DenyPrivateImageStyleDownload
*/
protected $policy;
/**
* A request object.
*
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* A response object.
*
* @var \Symfony\Component\HttpFoundation\Response
*/
protected $response;
/**
* The current route match.
*
* @var \Drupal\Core\Routing\RouteMatch|\PHPUnit\Framework\MockObject\MockObject
*/
protected $routeMatch;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->routeMatch = $this->createMock('Drupal\Core\Routing\RouteMatchInterface');
$this->policy = new DenyPrivateImageStyleDownload($this->routeMatch);
$this->response = new Response();
$this->request = new Request();
}
/**
* Asserts that caching is denied on the private image style download route.
*
* @dataProvider providerPrivateImageStyleDownloadPolicy
* @covers ::check
*/
public function testPrivateImageStyleDownloadPolicy($expected_result, $route_name): void {
$this->routeMatch->expects($this->once())
->method('getRouteName')
->willReturn($route_name);
$actual_result = $this->policy->check($this->response, $this->request);
$this->assertSame($expected_result, $actual_result);
}
/**
* Provides data and expected results for the test method.
*
* @return array
* Data and expected results.
*/
public static function providerPrivateImageStyleDownloadPolicy() {
return [
[ResponsePolicyInterface::DENY, 'image.style_private'],
[NULL, 'some.other.route'],
[NULL, NULL],
[NULL, FALSE],
[NULL, TRUE],
[NULL, new \StdClass()],
[NULL, [1, 2, 3]],
];
}
}