3 namespace Drupal\Tests\block\Functional;
5 use Drupal\Component\Utility\Html;
6 use Drupal\block\Entity\Block;
8 use Drupal\user\Entity\Role;
9 use Drupal\user\RoleInterface;
12 * Tests basic block functionality.
16 class BlockTest extends BlockTestBase {
19 * Tests block visibility.
21 public function testBlockVisibility() {
22 $block_name = 'system_powered_by_block';
23 // Create a random title for the block.
24 $title = $this->randomMachineName(8);
25 // Enable a standard block.
26 $default_theme = $this->config('system.theme')->get('default');
28 'id' => strtolower($this->randomMachineName(8)),
29 'region' => 'sidebar_first',
30 'settings[label]' => $title,
31 'settings[label_display]' => TRUE,
33 // Set the block to be hidden on any user path, and to be shown only to
34 // authenticated users.
35 $edit['visibility[request_path][pages]'] = '/user*';
36 $edit['visibility[request_path][negate]'] = TRUE;
37 $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
38 $this->drupalGet('admin/structure/block/add/' . $block_name . '/' . $default_theme);
39 $this->assertFieldChecked('edit-visibility-request-path-negate-0');
41 $this->drupalPostForm(NULL, $edit, t('Save block'));
42 $this->assertText('The block configuration has been saved.', 'Block was saved');
44 $this->clickLink('Configure');
45 $this->assertFieldChecked('edit-visibility-request-path-negate-1');
48 $this->assertText($title, 'Block was displayed on the front page.');
50 $this->drupalGet('user');
51 $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
53 // Confirm that the block is not displayed to anonymous users.
54 $this->drupalLogout();
56 $this->assertNoText($title, 'Block was not displayed to anonymous users.');
58 // Confirm that an empty block is not displayed.
59 $this->assertNoText('Powered by Drupal', 'Empty block not displayed.');
60 $this->assertNoRaw('sidebar-first', 'Empty sidebar-first region is not displayed.');
64 * Tests that visibility can be properly toggled.
66 public function testBlockToggleVisibility() {
67 $block_name = 'system_powered_by_block';
68 // Create a random title for the block.
69 $title = $this->randomMachineName(8);
70 // Enable a standard block.
71 $default_theme = $this->config('system.theme')->get('default');
73 'id' => strtolower($this->randomMachineName(8)),
74 'region' => 'sidebar_first',
75 'settings[label]' => $title,
77 $block_id = $edit['id'];
78 // Set the block to be shown only to authenticated users.
79 $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
80 $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
81 $this->clickLink('Configure');
82 $this->assertFieldChecked('edit-visibility-user-role-roles-authenticated');
85 'visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']' => FALSE,
87 $this->drupalPostForm(NULL, $edit, 'Save block');
88 $this->clickLink('Configure');
89 $this->assertNoFieldChecked('edit-visibility-user-role-roles-authenticated');
91 // Ensure that no visibility is configured.
92 /** @var \Drupal\block\BlockInterface $block */
93 $block = Block::load($block_id);
94 $visibility_config = $block->getVisibilityConditions()->getConfiguration();
95 $this->assertIdentical([], $visibility_config);
96 $this->assertIdentical([], $block->get('visibility'));
100 * Test block visibility when leaving "pages" textarea empty.
102 public function testBlockVisibilityListedEmpty() {
103 $block_name = 'system_powered_by_block';
104 // Create a random title for the block.
105 $title = $this->randomMachineName(8);
106 // Enable a standard block.
107 $default_theme = $this->config('system.theme')->get('default');
109 'id' => strtolower($this->randomMachineName(8)),
110 'region' => 'sidebar_first',
111 'settings[label]' => $title,
112 'visibility[request_path][negate]' => TRUE,
114 // Set the block to be hidden on any user path, and to be shown only to
115 // authenticated users.
116 $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
117 $this->assertText('The block configuration has been saved.', 'Block was saved');
119 $this->drupalGet('user');
120 $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
122 $this->drupalGet('USER');
123 $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
125 // Confirm that the block is not displayed to anonymous users.
126 $this->drupalLogout();
127 $this->drupalGet('');
128 $this->assertNoText($title, 'Block was not displayed to anonymous users on the front page.');
132 * Tests adding a block from the library page with a weight query string.
134 public function testAddBlockFromLibraryWithWeight() {
135 $default_theme = $this->config('system.theme')->get('default');
136 // Test one positive, zero, and one negative weight.
137 foreach (['7', '0', '-9'] as $weight) {
140 'region' => 'sidebar_first',
144 $this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme], $options));
146 $block_name = 'system_powered_by_block';
147 $add_url = Url::fromRoute('block.admin_add', [
148 'plugin_id' => $block_name,
149 'theme' => $default_theme
151 $links = $this->xpath('//a[contains(@href, :href)]', [':href' => $add_url->toString()]);
152 $this->assertEqual(1, count($links), 'Found one matching link.');
153 $this->assertEqual(t('Place block'), $links[0]->getText(), 'Found the expected link text.');
155 list($path, $query_string) = explode('?', $links[0]->getAttribute('href'), 2);
156 parse_str($query_string, $query_parts);
157 $this->assertEqual($weight, $query_parts['weight'], 'Found the expected weight query string.');
159 // Create a random title for the block.
160 $title = $this->randomMachineName(8);
161 $block_id = strtolower($this->randomMachineName(8));
164 'settings[label]' => $title,
166 // Create the block using the link parsed from the library page.
167 $this->drupalPostForm($this->getAbsoluteUrl($links[0]->getAttribute('href')), $edit, t('Save block'));
169 // Ensure that the block was created with the expected weight.
170 /** @var \Drupal\block\BlockInterface $block */
171 $block = Block::load($block_id);
172 $this->assertEqual($weight, $block->getWeight(), 'Found the block with expected weight.');
177 * Test configuring and moving a module-define block to specific regions.
179 public function testBlock() {
180 // Place page title block to test error messages.
181 $this->drupalPlaceBlock('page_title_block');
183 // Disable the block.
184 $this->drupalGet('admin/structure/block');
185 $this->clickLink('Disable');
187 // Select the 'Powered by Drupal' block to be configured and moved.
189 $block['id'] = 'system_powered_by_block';
190 $block['settings[label]'] = $this->randomMachineName(8);
191 $block['settings[label_display]'] = TRUE;
192 $block['theme'] = $this->config('system.theme')->get('default');
193 $block['region'] = 'header';
195 // Set block title to confirm that interface works and override any custom titles.
196 $this->drupalPostForm('admin/structure/block/add/' . $block['id'] . '/' . $block['theme'], ['settings[label]' => $block['settings[label]'], 'settings[label_display]' => $block['settings[label_display]'], 'id' => $block['id'], 'region' => $block['region']], t('Save block'));
197 $this->assertText(t('The block configuration has been saved.'), 'Block title set.');
198 // Check to see if the block was created by checking its configuration.
199 $instance = Block::load($block['id']);
201 $this->assertEqual($instance->label(), $block['settings[label]'], 'Stored block title found.');
203 // Check whether the block can be moved to all available regions.
204 foreach ($this->regions as $region) {
205 $this->moveBlockToRegion($block, $region);
208 // Disable the block.
209 $this->drupalGet('admin/structure/block');
210 $this->clickLink('Disable');
212 // Confirm that the block is now listed as disabled.
213 $this->assertText(t('The block settings have been updated.'), 'Block successfully moved to disabled region.');
215 // Confirm that the block instance title and markup are not displayed.
216 $this->drupalGet('node');
217 $this->assertNoText(t($block['settings[label]']));
218 // Check for <div id="block-my-block-instance-name"> if the machine name
219 // is my_block_instance_name.
220 $xpath = $this->buildXPathQuery('//div[@id=:id]/*', [':id' => 'block-' . str_replace('_', '-', strtolower($block['id']))]);
221 $this->assertNoFieldByXPath($xpath, FALSE, 'Block found in no regions.');
223 // Test deleting the block from the edit form.
224 $this->drupalGet('admin/structure/block/manage/' . $block['id']);
225 $this->clickLink(t('Remove block'));
226 $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block['settings[label]']]));
227 $this->drupalPostForm(NULL, [], t('Remove'));
228 $this->assertRaw(t('The block %name has been removed.', ['%name' => $block['settings[label]']]));
230 // Test deleting a block via "Configure block" link.
231 $block = $this->drupalPlaceBlock('system_powered_by_block');
232 $this->drupalGet('admin/structure/block/manage/' . $block->id(), ['query' => ['destination' => 'admin']]);
233 $this->clickLink(t('Remove block'));
234 $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block->label()]));
235 $this->drupalPostForm(NULL, [], t('Remove'));
236 $this->assertRaw(t('The block %name has been removed.', ['%name' => $block->label()]));
237 $this->assertUrl('admin');
238 $this->assertNoRaw($block->id());
242 * Tests that the block form has a theme selector when not passed via the URL.
244 public function testBlockThemeSelector() {
245 // Install all themes.
246 \Drupal::service('theme_handler')->install(['bartik', 'seven', 'stark']);
247 $theme_settings = $this->config('system.theme');
248 foreach (['bartik', 'seven', 'stark'] as $theme) {
249 $this->drupalGet('admin/structure/block/list/' . $theme);
250 $this->assertTitle(t('Block layout') . ' | Drupal');
251 // Select the 'Powered by Drupal' block to be placed.
253 $block['id'] = strtolower($this->randomMachineName());
254 $block['theme'] = $theme;
255 $block['region'] = 'content';
256 $this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
257 $this->assertText(t('The block configuration has been saved.'));
258 $this->assertUrl('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));
260 // Set the default theme and ensure the block is placed.
261 $theme_settings->set('default', $theme)->save();
262 $this->drupalGet('');
263 $elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]);
264 $this->assertTrue(!empty($elements), 'The block was found.');
269 * Test block display of theme titles.
271 public function testThemeName() {
272 // Enable the help block.
273 $this->drupalPlaceBlock('help_block', ['region' => 'help']);
274 $this->drupalPlaceBlock('local_tasks_block');
275 // Explicitly set the default and admin themes.
276 $theme = 'block_test_specialchars_theme';
277 \Drupal::service('theme_handler')->install([$theme]);
278 \Drupal::service('router.builder')->rebuild();
279 $this->drupalGet('admin/structure/block');
280 $this->assertEscaped('<"Cat" & \'Mouse\'>');
281 $this->drupalGet('admin/structure/block/list/block_test_specialchars_theme');
282 $this->assertEscaped('Demonstrate block regions (<"Cat" & \'Mouse\'>)');
286 * Test block title display settings.
288 public function testHideBlockTitle() {
289 $block_name = 'system_powered_by_block';
290 // Create a random title for the block.
291 $title = $this->randomMachineName(8);
292 $id = strtolower($this->randomMachineName(8));
293 // Enable a standard block.
294 $default_theme = $this->config('system.theme')->get('default');
297 'region' => 'sidebar_first',
298 'settings[label]' => $title,
300 $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
301 $this->assertText('The block configuration has been saved.', 'Block was saved');
303 $this->drupalGet('user');
304 $this->assertNoText($title, 'Block title was not displayed by default.');
307 'settings[label_display]' => TRUE,
309 $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
310 $this->assertText('The block configuration has been saved.', 'Block was saved');
312 $this->drupalGet('admin/structure/block/manage/' . $id);
313 $this->assertFieldChecked('edit-settings-label-display', 'The display_block option has the correct default value on the configuration form.');
315 $this->drupalGet('user');
316 $this->assertText($title, 'Block title was displayed when enabled.');
320 * Moves a block to a given region via the UI and confirms the result.
322 * @param array $block
323 * An array of information about the block, including the following keys:
324 * - module: The module providing the block.
325 * - title: The title of the block.
326 * - delta: The block's delta key.
327 * @param string $region
328 * The machine name of the theme region to move the block to, for example
329 * 'header' or 'sidebar_first'.
331 public function moveBlockToRegion(array $block, $region) {
332 // Set the created block to a specific region.
333 $block += ['theme' => $this->config('system.theme')->get('default')];
335 $edit['blocks[' . $block['id'] . '][region]'] = $region;
336 $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
338 // Confirm that the block was moved to the proper region.
339 $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', ['%region_name' => $region]));
341 // Confirm that the block is being displayed.
342 $this->drupalGet('');
343 $this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.');
345 // Confirm that the custom block was found at the proper region.
346 $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [
347 ':region-class' => 'region region-' . Html::getClass($region),
348 ':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])),
350 $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)]));
354 * Test that cache tags are properly set and bubbled up to the page cache.
356 * Verify that invalidation of these cache tags works:
357 * - "block:<block ID>"
358 * - "block_plugin:<block plugin ID>"
360 public function testBlockCacheTags() {
361 // The page cache only works for anonymous users.
362 $this->drupalLogout();
364 // Enable page caching.
365 $config = $this->config('system.performance');
366 $config->set('cache.page.max_age', 300);
369 // Place the "Powered by Drupal" block.
370 $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
372 // Prime the page cache.
373 $this->drupalGet('<front>');
374 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
376 // Verify a cache hit, but also the presence of the correct cache tags in
377 // both the page and block caches.
378 $this->drupalGet('<front>');
379 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
380 $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
381 $cid = implode(':', $cid_parts);
382 $cache_entry = \Drupal::cache('page')->get($cid);
383 $expected_cache_tags = [
386 'config:block.block.powered',
387 'config:user.role.anonymous',
391 sort($expected_cache_tags);
392 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
393 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
394 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
395 $expected_cache_tags = [
397 'config:block.block.powered',
400 sort($expected_cache_tags);
401 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
403 // The "Powered by Drupal" block is modified; verify a cache miss.
404 $block->setRegion('content');
406 $this->drupalGet('<front>');
407 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
409 // Now we should have a cache hit again.
410 $this->drupalGet('<front>');
411 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
413 // Place the "Powered by Drupal" block another time; verify a cache miss.
414 $block_2 = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']);
415 $this->drupalGet('<front>');
416 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
418 // Verify a cache hit, but also the presence of the correct cache tags.
419 $this->drupalGet('<front>');
420 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
421 $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
422 $cid = implode(':', $cid_parts);
423 $cache_entry = \Drupal::cache('page')->get($cid);
424 $expected_cache_tags = [
427 'config:block.block.powered',
428 'config:block.block.powered-2',
429 'config:user.role.anonymous',
433 sort($expected_cache_tags);
434 $this->assertEqual($cache_entry->tags, $expected_cache_tags);
435 $expected_cache_tags = [
437 'config:block.block.powered',
440 sort($expected_cache_tags);
441 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
442 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
443 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
444 $expected_cache_tags = [
446 'config:block.block.powered-2',
449 sort($expected_cache_tags);
450 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
451 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
452 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
454 // Now we should have a cache hit again.
455 $this->drupalGet('<front>');
456 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
458 // Delete the "Powered by Drupal" blocks; verify a cache miss.
459 entity_delete_multiple('block', ['powered', 'powered-2']);
460 $this->drupalGet('<front>');
461 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
465 * Tests that a link exists to block layout from the appearance form.
467 public function testThemeAdminLink() {
468 $this->drupalPlaceBlock('help_block', ['region' => 'help']);
469 $theme_admin = $this->drupalCreateUser([
472 'access administration pages',
474 $this->drupalLogin($theme_admin);
475 $this->drupalGet('admin/appearance');
476 $this->assertText('You can place blocks for each theme on the block layout page');
477 $this->assertLinkByHref('admin/structure/block');
481 * Tests that uninstalling a theme removes its block configuration.
483 public function testUninstallTheme() {
484 /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
485 $theme_handler = \Drupal::service('theme_handler');
487 $theme_handler->install(['seven']);
488 $this->config('system.theme')->set('default', 'seven')->save();
489 $block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']);
490 $this->drupalGet('<front>');
491 $this->assertText('Powered by Drupal');
493 $this->config('system.theme')->set('default', 'classy')->save();
494 $theme_handler->uninstall(['seven']);
496 // Ensure that the block configuration does not exist anymore.
497 $this->assertIdentical(NULL, Block::load($block->id()));
501 * Tests the block access.
503 public function testBlockAccess() {
504 $this->drupalPlaceBlock('test_access', ['region' => 'help']);
506 $this->drupalGet('<front>');
507 $this->assertNoText('Hello test world');
509 \Drupal::state()->set('test_block_access', TRUE);
510 $this->drupalGet('<front>');
511 $this->assertText('Hello test world');
515 * Tests block_user_role_delete.
517 public function testBlockUserRoleDelete() {
518 $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
521 $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
524 $block = Block::create([
525 'id' => $this->randomMachineName(),
526 'plugin' => 'system_powered_by_block',
529 $block->setVisibilityConfig('user_role', [
531 $role1->id() => $role1->id(),
532 $role2->id() => $role2->id(),
538 $this->assertEqual($block->getVisibility()['user_role']['roles'], [
539 $role1->id() => $role1->id(),
540 $role2->id() => $role2->id()
545 $block = Block::load($block->id());
546 $this->assertEqual($block->getVisibility()['user_role']['roles'], [
547 $role2->id() => $role2->id()