3 namespace Drupal\Tests\block\Functional;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Tests\BrowserTestBase;
9 * Tests that the block configuration UI exists and stores data correctly.
13 class BlockUiTest extends BrowserTestBase {
20 public static $modules = ['block', 'block_test', 'help', 'condition_test'];
25 * The submitted block values used by this test.
29 protected $blockValues;
32 * The block entities used by this test.
34 * @var \Drupal\block\BlockInterface[]
39 * An administrative user to configure the test environment.
43 protected function setUp() {
45 // Create and log in an administrative user.
46 $this->adminUser = $this->drupalCreateUser([
48 'access administration pages',
50 $this->drupalLogin($this->adminUser);
52 // Enable some test blocks.
53 $this->blockValues = [
57 'plugin_id' => 'system_menu_block:tools',
58 'settings' => ['region' => 'sidebar_second', 'id' => 'tools'],
59 'test_weight' => '-1',
62 'label' => 'Powered by Drupal',
64 'plugin_id' => 'system_powered_by_block',
65 'settings' => ['region' => 'footer', 'id' => 'powered'],
70 foreach ($this->blockValues as $values) {
71 $this->blocks[] = $this->drupalPlaceBlock($values['plugin_id'], $values['settings']);
76 * Test block demo page exists and functions correctly.
78 public function testBlockDemoUiPage() {
79 $this->drupalPlaceBlock('help_block', ['region' => 'help']);
80 $this->drupalGet('admin/structure/block');
81 $this->clickLink(t('Demonstrate block regions (@theme)', ['@theme' => 'Classy']));
82 $elements = $this->xpath('//div[contains(@class, "region-highlighted")]/div[contains(@class, "block-region") and contains(text(), :title)]', [':title' => 'Highlighted']);
83 $this->assertTrue(!empty($elements), 'Block demo regions are shown.');
85 \Drupal::service('theme_handler')->install(['test_theme']);
86 $this->drupalGet('admin/structure/block/demo/test_theme');
87 $this->assertEscaped('<strong>Test theme</strong>');
89 \Drupal::service('theme_handler')->install(['stable']);
90 $this->drupalGet('admin/structure/block/demo/stable');
91 $this->assertResponse(404, 'Hidden themes that are not the default theme are not supported by the block demo screen');
95 * Test block admin page exists and functions correctly.
97 public function testBlockAdminUiPage() {
98 // Visit the blocks admin ui.
99 $this->drupalGet('admin/structure/block');
100 // Look for the blocks table.
101 $blocks_table = $this->xpath("//table[@id='blocks']");
102 $this->assertTrue(!empty($blocks_table), 'The blocks table is being rendered.');
103 // Look for test blocks in the table.
104 foreach ($this->blockValues as $delta => $values) {
105 $block = $this->blocks[$delta];
106 $label = $block->label();
107 $element = $this->xpath('//*[@id="blocks"]/tbody/tr[' . $values['tr'] . ']/td[1]/text()');
108 $this->assertEquals($element[0]->getText(), $label, 'The "' . $label . '" block title is set inside the ' . $values['settings']['region'] . ' region.');
109 // Look for a test block region select form element.
110 $this->assertField('blocks[' . $values['settings']['id'] . '][region]', 'The block "' . $values['label'] . '" has a region assignment field.');
111 // Move the test block to the header region.
112 $edit['blocks[' . $values['settings']['id'] . '][region]'] = 'header';
113 // Look for a test block weight select form element.
114 $this->assertField('blocks[' . $values['settings']['id'] . '][weight]', 'The block "' . $values['label'] . '" has a weight assignment field.');
115 // Change the test block's weight.
116 $edit['blocks[' . $values['settings']['id'] . '][weight]'] = $values['test_weight'];
118 $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
119 foreach ($this->blockValues as $values) {
120 // Check if the region and weight settings changes have persisted.
121 $this->assertOptionSelected(
122 'edit-blocks-' . $values['settings']['id'] . '-region',
124 'The block "' . $label . '" has the correct region assignment (header).'
126 $this->assertOptionSelected(
127 'edit-blocks-' . $values['settings']['id'] . '-weight',
128 $values['test_weight'],
129 'The block "' . $label . '" has the correct weight assignment (' . $values['test_weight'] . ').'
133 // Add a block with a machine name the same as a region name.
134 $this->drupalPlaceBlock('system_powered_by_block', ['region' => 'header', 'id' => 'header']);
135 $this->drupalGet('admin/structure/block');
136 $element = $this->xpath('//tr[contains(@class, :class)]', [':class' => 'region-title-header']);
137 $this->assertTrue(!empty($element));
139 // Ensure hidden themes do not appear in the UI. Enable another non base
140 // theme and place the local tasks block.
141 $this->assertTrue(\Drupal::service('theme_handler')->themeExists('classy'), 'The classy base theme is enabled');
142 $this->drupalPlaceBlock('local_tasks_block', ['region' => 'header']);
143 \Drupal::service('theme_installer')->install(['stable', 'stark']);
144 $this->drupalGet('admin/structure/block');
145 $theme_handler = \Drupal::service('theme_handler');
146 $this->assertLink($theme_handler->getName('classy'));
147 $this->assertLink($theme_handler->getName('stark'));
148 $this->assertNoLink($theme_handler->getName('stable'));
150 $this->drupalGet('admin/structure/block/list/stable');
151 $this->assertResponse(404, 'Placing blocks through UI is not possible for a hidden base theme.');
153 \Drupal::configFactory()->getEditable('system.theme')->set('admin', 'stable')->save();
154 \Drupal::service('router.builder')->rebuildIfNeeded();
155 $this->drupalPlaceBlock('local_tasks_block', ['region' => 'header', 'theme' => 'stable']);
156 $this->drupalGet('admin/structure/block');
157 $this->assertLink($theme_handler->getName('stable'));
158 $this->drupalGet('admin/structure/block/list/stable');
159 $this->assertResponse(200, 'Placing blocks through UI is possible for a hidden base theme that is the admin theme.');
163 * Tests the block categories on the listing page.
165 public function testCandidateBlockList() {
167 ':title' => 'Display message',
168 ':category' => 'Block test',
169 ':href' => 'admin/structure/block/add/test_block_instantiation/classy',
171 $pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]';
173 $this->drupalGet('admin/structure/block');
174 $this->clickLink('Place block');
175 $elements = $this->xpath($pattern, $arguments);
176 $this->assertTrue(!empty($elements), 'The test block appears in the category for its module.');
178 // Trigger the custom category addition in block_test_block_alter().
179 $this->container->get('state')->set('block_test_info_alter', TRUE);
180 $this->container->get('plugin.manager.block')->clearCachedDefinitions();
182 $this->drupalGet('admin/structure/block');
183 $this->clickLink('Place block');
184 $arguments[':category'] = 'Custom category';
185 $elements = $this->xpath($pattern, $arguments);
186 $this->assertTrue(!empty($elements), 'The test block appears in a custom category controlled by block_test_block_alter().');
190 * Tests the behavior of unsatisfied context-aware blocks.
192 public function testContextAwareUnsatisfiedBlocks() {
194 ':category' => 'Block test',
195 ':href' => 'admin/structure/block/add/test_context_aware_unsatisfied/classy',
196 ':text' => 'Test context-aware unsatisfied block',
199 $this->drupalGet('admin/structure/block');
200 $this->clickLink('Place block');
201 $elements = $this->xpath('//tr[.//td/div[text()=:text] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]', $arguments);
202 $this->assertTrue(empty($elements), 'The context-aware test block does not appear.');
204 $definition = \Drupal::service('plugin.manager.block')->getDefinition('test_context_aware_unsatisfied');
205 $this->assertTrue(!empty($definition), 'The context-aware test block does not exist.');
209 * Tests the behavior of context-aware blocks.
211 public function testContextAwareBlocks() {
212 $expected_text = '<div id="test_context_aware--username">' . \Drupal::currentUser()->getUsername() . '</div>';
213 $this->drupalGet('');
214 $this->assertNoText('Test context-aware block');
215 $this->assertNoRaw($expected_text);
217 $block_url = 'admin/structure/block/add/test_context_aware/classy';
219 ':title' => 'Test context-aware block',
220 ':category' => 'Block test',
221 ':href' => $block_url,
223 $pattern = '//tr[.//td/div[text()=:title] and .//td[text()=:category] and .//td//a[contains(@href, :href)]]';
225 $this->drupalGet('admin/structure/block');
226 $this->clickLink('Place block');
227 $elements = $this->xpath($pattern, $arguments);
228 $this->assertTrue(!empty($elements), 'The context-aware test block appears.');
229 $definition = \Drupal::service('plugin.manager.block')->getDefinition('test_context_aware');
230 $this->assertTrue(!empty($definition), 'The context-aware test block exists.');
232 'region' => 'content',
233 'settings[context_mapping][user]' => '@block_test.multiple_static_context:userB',
235 $this->drupalPostForm($block_url, $edit, 'Save block');
237 $this->drupalGet('');
238 $this->assertText('Test context-aware block');
239 $this->assertText('User context found.');
240 $this->assertRaw($expected_text);
242 // Test context mapping allows empty selection for optional contexts.
243 $this->drupalGet('admin/structure/block/manage/testcontextawareblock');
245 'settings[context_mapping][user]' => '',
247 $this->drupalPostForm(NULL, $edit, 'Save block');
248 $this->drupalGet('');
249 $this->assertText('No context mapping selected.');
250 $this->assertNoText('User context found.');
252 // Tests that conditions with missing context are not displayed.
253 $this->drupalGet('admin/structure/block/manage/testcontextawareblock');
254 $this->assertNoRaw('No existing type');
255 $this->assertNoFieldByXPath('//*[@name="visibility[condition_test_no_existing_type][negate]"]');
259 * Tests that the BlockForm populates machine name correctly.
261 public function testMachineNameSuggestion() {
262 $url = 'admin/structure/block/add/test_block_instantiation/classy';
263 $this->drupalGet($url);
264 $this->assertFieldByName('id', 'displaymessage', 'Block form uses raw machine name suggestion when no instance already exists.');
265 $edit = ['region' => 'content'];
266 $this->drupalPostForm($url, $edit, 'Save block');
267 $this->assertText('The block configuration has been saved.');
269 // Now, check to make sure the form starts by autoincrementing correctly.
270 $this->drupalGet($url);
271 $this->assertFieldByName('id', 'displaymessage_2', 'Block form appends _2 to plugin-suggested machine name when an instance already exists.');
272 $this->drupalPostForm($url, $edit, 'Save block');
273 $this->assertText('The block configuration has been saved.');
275 // And verify that it continues working beyond just the first two.
276 $this->drupalGet($url);
277 $this->assertFieldByName('id', 'displaymessage_3', 'Block form appends _3 to plugin-suggested machine name when two instances already exist.');
281 * Tests the block placement indicator.
283 public function testBlockPlacementIndicator() {
284 // Select the 'Powered by Drupal' block to be placed.
286 $block['id'] = strtolower($this->randomMachineName());
287 $block['theme'] = 'classy';
288 $block['region'] = 'content';
290 // After adding a block, it will indicate which block was just added.
291 $this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
292 $this->assertUrl('admin/structure/block/list/classy?block-placement=' . Html::getClass($block['id']));
294 // Resaving the block page will remove the block indicator.
295 $this->drupalPostForm(NULL, [], t('Save blocks'));
296 $this->assertUrl('admin/structure/block/list/classy');
300 * Tests if validation errors are passed plugin form to the parent form.
302 public function testBlockValidateErrors() {
303 $this->drupalPostForm('admin/structure/block/add/test_settings_validation/classy', ['region' => 'content', 'settings[digits]' => 'abc'], t('Save block'));
305 $arguments = [':message' => 'Only digits are allowed'];
306 $pattern = '//div[contains(@class,"messages messages--error")]/div[contains(text()[2],:message)]';
307 $elements = $this->xpath($pattern, $arguments);
308 $this->assertTrue($elements, 'Plugin error message found in parent form.');
310 $error_class_pattern = '//div[contains(@class,"form-item-settings-digits")]/input[contains(@class,"error")]';
311 $error_class = $this->xpath($error_class_pattern);
312 $this->assertTrue($error_class, 'Plugin error class found in parent form.');
316 * Tests that the enable/disable routes are protected from CSRF.
318 public function testRouteProtection() {
319 // Get the first block generated in our setUp method.
320 /** @var \Drupal\block\BlockInterface $block */
321 $block = reset($this->blocks);
322 // Ensure that the enable and disable routes are protected.
323 $this->drupalGet('admin/structure/block/manage/' . $block->id() . '/disable');
324 $this->assertResponse(403);
325 $this->drupalGet('admin/structure/block/manage/' . $block->id() . '/enable');
326 $this->assertResponse(403);