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 the block operation links.
244 public function testBlockOperationLinks() {
245 $this->drupalGet('admin/structure/block');
246 // Go to the select block form.
247 $this->clickLink('Place block');
248 // Select the first available block.
249 $this->clickLink('Place block');
250 // Finally place the block
251 $this->submitForm([], 'Save block');
253 $url = $this->getUrl();
254 $parsed = parse_url($url);
255 $this->assertContains('block-placement', $parsed['query']);
257 $this->clickLink('Remove');
258 $this->submitForm([], 'Remove');
260 $url = $this->getUrl();
261 $parsed = parse_url($url);
262 $this->assertTrue(empty($parsed['query']));
266 * Tests that the block form has a theme selector when not passed via the URL.
268 public function testBlockThemeSelector() {
269 // Install all themes.
270 \Drupal::service('theme_handler')->install(['bartik', 'seven', 'stark']);
271 $theme_settings = $this->config('system.theme');
272 foreach (['bartik', 'seven', 'stark'] as $theme) {
273 $this->drupalGet('admin/structure/block/list/' . $theme);
274 $this->assertTitle(t('Block layout') . ' | Drupal');
275 // Select the 'Powered by Drupal' block to be placed.
277 $block['id'] = strtolower($this->randomMachineName());
278 $block['theme'] = $theme;
279 $block['region'] = 'content';
280 $this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
281 $this->assertText(t('The block configuration has been saved.'));
282 $this->assertUrl('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));
284 // Set the default theme and ensure the block is placed.
285 $theme_settings->set('default', $theme)->save();
286 $this->drupalGet('');
287 $elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]);
288 $this->assertTrue(!empty($elements), 'The block was found.');
293 * Test block display of theme titles.
295 public function testThemeName() {
296 // Enable the help block.
297 $this->drupalPlaceBlock('help_block', ['region' => 'help']);
298 $this->drupalPlaceBlock('local_tasks_block');
299 // Explicitly set the default and admin themes.
300 $theme = 'block_test_specialchars_theme';
301 \Drupal::service('theme_handler')->install([$theme]);
302 \Drupal::service('router.builder')->rebuild();
303 $this->drupalGet('admin/structure/block');
304 $this->assertEscaped('<"Cat" & \'Mouse\'>');
305 $this->drupalGet('admin/structure/block/list/block_test_specialchars_theme');
306 $this->assertEscaped('Demonstrate block regions (<"Cat" & \'Mouse\'>)');
310 * Test block title display settings.
312 public function testHideBlockTitle() {
313 $block_name = 'system_powered_by_block';
314 // Create a random title for the block.
315 $title = $this->randomMachineName(8);
316 $id = strtolower($this->randomMachineName(8));
317 // Enable a standard block.
318 $default_theme = $this->config('system.theme')->get('default');
321 'region' => 'sidebar_first',
322 'settings[label]' => $title,
324 $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
325 $this->assertText('The block configuration has been saved.', 'Block was saved');
327 $this->drupalGet('user');
328 $this->assertNoText($title, 'Block title was not displayed by default.');
331 'settings[label_display]' => TRUE,
333 $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
334 $this->assertText('The block configuration has been saved.', 'Block was saved');
336 $this->drupalGet('admin/structure/block/manage/' . $id);
337 $this->assertFieldChecked('edit-settings-label-display', 'The display_block option has the correct default value on the configuration form.');
339 $this->drupalGet('user');
340 $this->assertText($title, 'Block title was displayed when enabled.');
344 * Moves a block to a given region via the UI and confirms the result.
346 * @param array $block
347 * An array of information about the block, including the following keys:
348 * - module: The module providing the block.
349 * - title: The title of the block.
350 * - delta: The block's delta key.
351 * @param string $region
352 * The machine name of the theme region to move the block to, for example
353 * 'header' or 'sidebar_first'.
355 public function moveBlockToRegion(array $block, $region) {
356 // Set the created block to a specific region.
357 $block += ['theme' => $this->config('system.theme')->get('default')];
359 $edit['blocks[' . $block['id'] . '][region]'] = $region;
360 $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
362 // Confirm that the block was moved to the proper region.
363 $this->assertText(t('The block settings have been updated.'), format_string('Block successfully moved to %region_name region.', ['%region_name' => $region]));
365 // Confirm that the block is being displayed.
366 $this->drupalGet('');
367 $this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.');
369 // Confirm that the custom block was found at the proper region.
370 $xpath = $this->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [
371 ':region-class' => 'region region-' . Html::getClass($region),
372 ':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])),
374 $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)]));
378 * Test that cache tags are properly set and bubbled up to the page cache.
380 * Verify that invalidation of these cache tags works:
381 * - "block:<block ID>"
382 * - "block_plugin:<block plugin ID>"
384 public function testBlockCacheTags() {
385 // The page cache only works for anonymous users.
386 $this->drupalLogout();
388 // Enable page caching.
389 $config = $this->config('system.performance');
390 $config->set('cache.page.max_age', 300);
393 // Place the "Powered by Drupal" block.
394 $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
396 // Prime the page cache.
397 $this->drupalGet('<front>');
398 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
400 // Verify a cache hit, but also the presence of the correct cache tags in
401 // both the page and block caches.
402 $this->drupalGet('<front>');
403 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
404 $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
405 $cid = implode(':', $cid_parts);
406 $cache_entry = \Drupal::cache('page')->get($cid);
407 $expected_cache_tags = [
410 'config:block.block.powered',
411 'config:user.role.anonymous',
415 sort($expected_cache_tags);
416 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
417 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
418 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
419 $expected_cache_tags = [
421 'config:block.block.powered',
424 sort($expected_cache_tags);
425 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
427 // The "Powered by Drupal" block is modified; verify a cache miss.
428 $block->setRegion('content');
430 $this->drupalGet('<front>');
431 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
433 // Now we should have a cache hit again.
434 $this->drupalGet('<front>');
435 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
437 // Place the "Powered by Drupal" block another time; verify a cache miss.
438 $block_2 = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']);
439 $this->drupalGet('<front>');
440 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
442 // Verify a cache hit, but also the presence of the correct cache tags.
443 $this->drupalGet('<front>');
444 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
445 $cid_parts = [\Drupal::url('<front>', [], ['absolute' => TRUE]), 'html'];
446 $cid = implode(':', $cid_parts);
447 $cache_entry = \Drupal::cache('page')->get($cid);
448 $expected_cache_tags = [
451 'config:block.block.powered',
452 'config:block.block.powered-2',
453 'config:user.role.anonymous',
457 sort($expected_cache_tags);
458 $this->assertEqual($cache_entry->tags, $expected_cache_tags);
459 $expected_cache_tags = [
461 'config:block.block.powered',
464 sort($expected_cache_tags);
465 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
466 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
467 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
468 $expected_cache_tags = [
470 'config:block.block.powered-2',
473 sort($expected_cache_tags);
474 $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
475 $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
476 $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
478 // Now we should have a cache hit again.
479 $this->drupalGet('<front>');
480 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
482 // Delete the "Powered by Drupal" blocks; verify a cache miss.
483 entity_delete_multiple('block', ['powered', 'powered-2']);
484 $this->drupalGet('<front>');
485 $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
489 * Tests that a link exists to block layout from the appearance form.
491 public function testThemeAdminLink() {
492 $this->drupalPlaceBlock('help_block', ['region' => 'help']);
493 $theme_admin = $this->drupalCreateUser([
496 'access administration pages',
498 $this->drupalLogin($theme_admin);
499 $this->drupalGet('admin/appearance');
500 $this->assertText('You can place blocks for each theme on the block layout page');
501 $this->assertLinkByHref('admin/structure/block');
505 * Tests that uninstalling a theme removes its block configuration.
507 public function testUninstallTheme() {
508 /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
509 $theme_handler = \Drupal::service('theme_handler');
511 $theme_handler->install(['seven']);
512 $this->config('system.theme')->set('default', 'seven')->save();
513 $block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']);
514 $this->drupalGet('<front>');
515 $this->assertText('Powered by Drupal');
517 $this->config('system.theme')->set('default', 'classy')->save();
518 $theme_handler->uninstall(['seven']);
520 // Ensure that the block configuration does not exist anymore.
521 $this->assertIdentical(NULL, Block::load($block->id()));
525 * Tests the block access.
527 public function testBlockAccess() {
528 $this->drupalPlaceBlock('test_access', ['region' => 'help']);
530 $this->drupalGet('<front>');
531 $this->assertNoText('Hello test world');
533 \Drupal::state()->set('test_block_access', TRUE);
534 $this->drupalGet('<front>');
535 $this->assertText('Hello test world');
539 * Tests block_user_role_delete.
541 public function testBlockUserRoleDelete() {
542 $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
545 $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
548 $block = Block::create([
549 'id' => $this->randomMachineName(),
550 'plugin' => 'system_powered_by_block',
553 $block->setVisibilityConfig('user_role', [
555 $role1->id() => $role1->id(),
556 $role2->id() => $role2->id(),
562 $this->assertEqual($block->getVisibility()['user_role']['roles'], [
563 $role1->id() => $role1->id(),
564 $role2->id() => $role2->id(),
569 $block = Block::load($block->id());
570 $this->assertEqual($block->getVisibility()['user_role']['roles'], [
571 $role2->id() => $role2->id(),