BlockTest.php 22.2 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\block\Functional;
4

5
use Drupal\Component\Render\FormattableMarkup;
6
use Drupal\Component\Utility\Html;
7
use Drupal\block\Entity\Block;
8
use Drupal\Core\Url;
9
use Drupal\user\Entity\Role;
10
use Drupal\user\RoleInterface;
11

12
/**
13 14 15
 * Tests basic block functionality.
 *
 * @group block
16 17
 */
class BlockTest extends BlockTestBase {
18

19 20 21 22 23
  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'classy';

24
  /**
25
   * Tests block visibility.
26
   */
27
  public function testBlockVisibility() {
28 29
    $block_name = 'system_powered_by_block';
    // Create a random title for the block.
30
    $title = $this->randomMachineName(8);
31
    // Enable a standard block.
32
    $default_theme = $this->config('system.theme')->get('default');
33
    $edit = [
34
      'id' => strtolower($this->randomMachineName(8)),
35
      'region' => 'sidebar_first',
36
      'settings[label]' => $title,
37
      'settings[label_display]' => TRUE,
38
    ];
39 40
    // Set the block to be hidden on any user path, and to be shown only to
    // authenticated users.
41
    $edit['visibility[request_path][pages]'] = '/user*';
42
    $edit['visibility[request_path][negate]'] = TRUE;
43
    $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
44
    $this->drupalGet('admin/structure/block/add/' . $block_name . '/' . $default_theme);
45
    $this->assertSession()->checkboxChecked('edit-visibility-request-path-negate-0');
46 47

    $this->drupalPostForm(NULL, $edit, t('Save block'));
48
    $this->assertText('The block configuration has been saved.', 'Block was saved');
49

50
    $this->clickLink('Configure');
51
    $this->assertSession()->checkboxChecked('edit-visibility-request-path-negate-1');
52

53
    $this->drupalGet('');
54
    $this->assertText($title, 'Block was displayed on the front page.');
55 56

    $this->drupalGet('user');
57
    $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
58 59 60 61

    // Confirm that the block is not displayed to anonymous users.
    $this->drupalLogout();
    $this->drupalGet('');
62
    $this->assertNoText($title, 'Block was not displayed to anonymous users.');
63 64

    // Confirm that an empty block is not displayed.
65
    $this->assertNoText('Powered by Drupal', 'Empty block not displayed.');
66
    $this->assertNoRaw('sidebar-first');
67 68
  }

69 70 71 72 73 74 75 76
  /**
   * Tests that visibility can be properly toggled.
   */
  public function testBlockToggleVisibility() {
    $block_name = 'system_powered_by_block';
    // Create a random title for the block.
    $title = $this->randomMachineName(8);
    // Enable a standard block.
77
    $default_theme = $this->config('system.theme')->get('default');
78
    $edit = [
79 80 81
      'id' => strtolower($this->randomMachineName(8)),
      'region' => 'sidebar_first',
      'settings[label]' => $title,
82
    ];
83 84
    $block_id = $edit['id'];
    // Set the block to be shown only to authenticated users.
85
    $edit['visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']'] = TRUE;
86 87
    $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
    $this->clickLink('Configure');
88
    $this->assertSession()->checkboxChecked('edit-visibility-user-role-roles-authenticated');
89 90

    $edit = [
91
      'visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']' => FALSE,
92 93 94
    ];
    $this->drupalPostForm(NULL, $edit, 'Save block');
    $this->clickLink('Configure');
95
    $this->assertSession()->checkboxNotChecked('edit-visibility-user-role-roles-authenticated');
96 97 98 99 100 101 102 103 104

    // Ensure that no visibility is configured.
    /** @var \Drupal\block\BlockInterface $block */
    $block = Block::load($block_id);
    $visibility_config = $block->getVisibilityConditions()->getConfiguration();
    $this->assertIdentical([], $visibility_config);
    $this->assertIdentical([], $block->get('visibility'));
  }

105
  /**
106
   * Test block visibility when leaving "pages" textarea empty.
107
   */
108
  public function testBlockVisibilityListedEmpty() {
109 110
    $block_name = 'system_powered_by_block';
    // Create a random title for the block.
111
    $title = $this->randomMachineName(8);
112
    // Enable a standard block.
113
    $default_theme = $this->config('system.theme')->get('default');
114
    $edit = [
115
      'id' => strtolower($this->randomMachineName(8)),
116
      'region' => 'sidebar_first',
117
      'settings[label]' => $title,
118
      'visibility[request_path][negate]' => TRUE,
119
    ];
120 121
    // Set the block to be hidden on any user path, and to be shown only to
    // authenticated users.
122
    $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
123
    $this->assertText('The block configuration has been saved.', 'Block was saved');
124

125
    $this->drupalGet('user');
126
    $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
127

128
    $this->drupalGet('USER');
129
    $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
130 131 132 133

    // Confirm that the block is not displayed to anonymous users.
    $this->drupalLogout();
    $this->drupalGet('');
134
    $this->assertNoText($title, 'Block was not displayed to anonymous users on the front page.');
135 136
  }

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  /**
   * Tests adding a block from the library page with a weight query string.
   */
  public function testAddBlockFromLibraryWithWeight() {
    $default_theme = $this->config('system.theme')->get('default');
    // Test one positive, zero, and one negative weight.
    foreach (['7', '0', '-9'] as $weight) {
      $options = [
        'query' => [
          'region' => 'sidebar_first',
          'weight' => $weight,
        ],
      ];
      $this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme], $options));

      $block_name = 'system_powered_by_block';
      $add_url = Url::fromRoute('block.admin_add', [
        'plugin_id' => $block_name,
155
        'theme' => $default_theme,
156 157
      ]);
      $links = $this->xpath('//a[contains(@href, :href)]', [':href' => $add_url->toString()]);
158
      $this->assertCount(1, $links, 'Found one matching link.');
159
      $this->assertEqual(t('Place block'), $links[0]->getText(), 'Found the expected link text.');
160

161
      list($path, $query_string) = explode('?', $links[0]->getAttribute('href'), 2);
162 163 164 165 166 167 168 169 170 171 172
      parse_str($query_string, $query_parts);
      $this->assertEqual($weight, $query_parts['weight'], 'Found the expected weight query string.');

      // Create a random title for the block.
      $title = $this->randomMachineName(8);
      $block_id = strtolower($this->randomMachineName(8));
      $edit = [
        'id' => $block_id,
        'settings[label]' => $title,
      ];
      // Create the block using the link parsed from the library page.
173
      $this->drupalPostForm($this->getAbsoluteUrl($links[0]->getAttribute('href')), $edit, t('Save block'));
174 175 176 177 178 179 180 181

      // Ensure that the block was created with the expected weight.
      /** @var \Drupal\block\BlockInterface $block */
      $block = Block::load($block_id);
      $this->assertEqual($weight, $block->getWeight(), 'Found the block with expected weight.');
    }
  }

182 183 184
  /**
   * Test configuring and moving a module-define block to specific regions.
   */
185
  public function testBlock() {
186 187 188
    // Place page title block to test error messages.
    $this->drupalPlaceBlock('page_title_block');

189 190 191 192
    // Disable the block.
    $this->drupalGet('admin/structure/block');
    $this->clickLink('Disable');

193
    // Select the 'Powered by Drupal' block to be configured and moved.
194
    $block = [];
195
    $block['id'] = 'system_powered_by_block';
196
    $block['settings[label]'] = $this->randomMachineName(8);
197
    $block['settings[label_display]'] = TRUE;
198
    $block['theme'] = $this->config('system.theme')->get('default');
199
    $block['region'] = 'header';
200 201

    // Set block title to confirm that interface works and override any custom titles.
202
    $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'));
203
    $this->assertText(t('The block configuration has been saved.'), 'Block title set.');
204
    // Check to see if the block was created by checking its configuration.
205
    $instance = Block::load($block['id']);
206

207
    $this->assertEqual($instance->label(), $block['settings[label]'], 'Stored block title found.');
208 209 210 211 212 213

    // Check whether the block can be moved to all available regions.
    foreach ($this->regions as $region) {
      $this->moveBlockToRegion($block, $region);
    }

214 215 216
    // Disable the block.
    $this->drupalGet('admin/structure/block');
    $this->clickLink('Disable');
217

218
    // Confirm that the block is now listed as disabled.
219
    $this->assertText(t('The block settings have been updated.'), 'Block successfully moved to disabled region.');
220

221 222
    // Confirm that the block instance title and markup are not displayed.
    $this->drupalGet('node');
223
    $this->assertNoText(t($block['settings[label]']));
224 225
    // Check for <div id="block-my-block-instance-name"> if the machine name
    // is my_block_instance_name.
226
    $xpath = $this->assertSession()->buildXPathQuery('//div[@id=:id]/*', [':id' => 'block-' . str_replace('_', '-', strtolower($block['id']))]);
227
    $this->assertSession()->elementNotExists('xpath', $xpath);
228 229

    // Test deleting the block from the edit form.
230
    $this->drupalGet('admin/structure/block/manage/' . $block['id']);
231
    $this->clickLink(t('Remove block'));
232 233 234
    $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block['settings[label]']]));
    $this->drupalPostForm(NULL, [], t('Remove'));
    $this->assertRaw(t('The block %name has been removed.', ['%name' => $block['settings[label]']]));
235 236 237

    // Test deleting a block via "Configure block" link.
    $block = $this->drupalPlaceBlock('system_powered_by_block');
238
    $this->drupalGet('admin/structure/block/manage/' . $block->id(), ['query' => ['destination' => 'admin']]);
239
    $this->clickLink(t('Remove block'));
240 241 242
    $this->assertRaw(t('Are you sure you want to remove the block @name?', ['@name' => $block->label()]));
    $this->drupalPostForm(NULL, [], t('Remove'));
    $this->assertRaw(t('The block %name has been removed.', ['%name' => $block->label()]));
243
    $this->assertSession()->addressEquals('admin');
244
    $this->assertNoRaw($block->id());
245 246
  }

247 248 249 250
  /**
   * Tests that the block form has a theme selector when not passed via the URL.
   */
  public function testBlockThemeSelector() {
251
    // Install all themes.
252
    \Drupal::service('theme_installer')->install(['bartik', 'seven', 'stark']);
253
    $theme_settings = $this->config('system.theme');
254
    foreach (['bartik', 'seven', 'stark'] as $theme) {
255
      $this->drupalGet('admin/structure/block/list/' . $theme);
256
      $this->assertSession()->titleEquals('Block layout | Drupal');
257
      // Select the 'Powered by Drupal' block to be placed.
258
      $block = [];
259
      $block['id'] = strtolower($this->randomMachineName());
260 261
      $block['theme'] = $theme;
      $block['region'] = 'content';
262
      $this->drupalPostForm('admin/structure/block/add/system_powered_by_block', $block, t('Save block'));
263
      $this->assertText(t('The block configuration has been saved.'));
264
      $this->assertSession()->addressEquals('admin/structure/block/list/' . $theme . '?block-placement=' . Html::getClass($block['id']));
265 266 267 268

      // Set the default theme and ensure the block is placed.
      $theme_settings->set('default', $theme)->save();
      $this->drupalGet('');
269
      $elements = $this->xpath('//div[@id = :id]', [':id' => Html::getUniqueId('block-' . $block['id'])]);
270 271 272 273
      $this->assertTrue(!empty($elements), 'The block was found.');
    }
  }

274 275 276
  /**
   * Test block display of theme titles.
   */
277
  public function testThemeName() {
278
    // Enable the help block.
279
    $this->drupalPlaceBlock('help_block', ['region' => 'help']);
280
    $this->drupalPlaceBlock('local_tasks_block');
281
    // Explicitly set the default and admin themes.
282
    $theme = 'block_test_specialchars_theme';
283
    \Drupal::service('theme_installer')->install([$theme]);
284
    $this->drupalGet('admin/structure/block');
285
    $this->assertSession()->assertEscaped('<"Cat" & \'Mouse\'>');
286
    $this->drupalGet('admin/structure/block/list/block_test_specialchars_theme');
287
    $this->assertSession()->assertEscaped('Demonstrate block regions (<"Cat" & \'Mouse\'>)');
288 289
  }

290 291 292
  /**
   * Test block title display settings.
   */
293
  public function testHideBlockTitle() {
294 295
    $block_name = 'system_powered_by_block';
    // Create a random title for the block.
296 297
    $title = $this->randomMachineName(8);
    $id = strtolower($this->randomMachineName(8));
298
    // Enable a standard block.
299
    $default_theme = $this->config('system.theme')->get('default');
300
    $edit = [
301
      'id' => $id,
302
      'region' => 'sidebar_first',
303
      'settings[label]' => $title,
304
    ];
305
    $this->drupalPostForm('admin/structure/block/add/' . $block_name . '/' . $default_theme, $edit, t('Save block'));
306 307 308
    $this->assertText('The block configuration has been saved.', 'Block was saved');

    $this->drupalGet('user');
309
    $this->assertNoText($title, 'Block title was not displayed by default.');
310

311
    $edit = [
312
      'settings[label_display]' => TRUE,
313
    ];
314
    $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
315 316
    $this->assertText('The block configuration has been saved.', 'Block was saved');

317
    $this->drupalGet('admin/structure/block/manage/' . $id);
318
    $this->assertSession()->checkboxChecked('edit-settings-label-display');
319

320
    $this->drupalGet('user');
321
    $this->assertText($title, 'Block title was displayed when enabled.');
322 323
  }

324 325 326 327 328 329 330 331 332 333 334 335
  /**
   * Moves a block to a given region via the UI and confirms the result.
   *
   * @param array $block
   *   An array of information about the block, including the following keys:
   *   - module: The module providing the block.
   *   - title: The title of the block.
   *   - delta: The block's delta key.
   * @param string $region
   *   The machine name of the theme region to move the block to, for example
   *   'header' or 'sidebar_first'.
   */
336
  public function moveBlockToRegion(array $block, $region) {
337
    // Set the created block to a specific region.
338 339
    $block += ['theme' => $this->config('system.theme')->get('default')];
    $edit = [];
340
    $edit['blocks[' . $block['id'] . '][region]'] = $region;
341
    $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
342 343

    // Confirm that the block was moved to the proper region.
344
    $this->assertText(t('The block settings have been updated.'), new FormattableMarkup('Block successfully moved to %region_name region.', ['%region_name' => $region]));
345 346

    // Confirm that the block is being displayed.
347
    $this->drupalGet('');
348
    $this->assertText(t($block['settings[label]']), 'Block successfully being displayed on the page.');
349 350

    // Confirm that the custom block was found at the proper region.
351
    $xpath = $this->assertSession()->buildXPathQuery('//div[@class=:region-class]//div[@id=:block-id]/*', [
352
      ':region-class' => 'region region-' . Html::getClass($region),
353
      ':block-id' => 'block-' . str_replace('_', '-', strtolower($block['id'])),
354
    ]);
355
    $this->assertSession()->elementExists('xpath', $xpath);
356 357 358
  }

  /**
359 360 361 362 363
   * Test that cache tags are properly set and bubbled up to the page cache.
   *
   * Verify that invalidation of these cache tags works:
   * - "block:<block ID>"
   * - "block_plugin:<block plugin ID>"
364
   */
365 366 367
  public function testBlockCacheTags() {
    // The page cache only works for anonymous users.
    $this->drupalLogout();
368

369
    // Enable page caching.
370
    $config = $this->config('system.performance');
371 372 373 374
    $config->set('cache.page.max_age', 300);
    $config->save();

    // Place the "Powered by Drupal" block.
375
    $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
376 377 378

    // Prime the page cache.
    $this->drupalGet('<front>');
379
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
380 381 382 383

    // Verify a cache hit, but also the presence of the correct cache tags in
    // both the page and block caches.
    $this->drupalGet('<front>');
384
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
385
    $cid_parts = [Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), ''];
386
    $cid = implode(':', $cid_parts);
387
    $cache_entry = \Drupal::cache('page')->get($cid);
388
    $expected_cache_tags = [
389
      'config:block_list',
390
      'block_view',
391
      'config:block.block.powered',
392
      'config:user.role.anonymous',
393
      'http_response',
394
      'rendered',
395
    ];
396
    sort($expected_cache_tags);
397
    $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
398
    $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
399
    $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
400
    $expected_cache_tags = [
401
      'block_view',
402
      'config:block.block.powered',
403
      'rendered',
404
    ];
405
    sort($expected_cache_tags);
406
    $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
407

408
    // The "Powered by Drupal" block is modified; verify a cache miss.
409
    $block->setRegion('content');
410
    $block->save();
411
    $this->drupalGet('<front>');
412
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
413 414 415

    // Now we should have a cache hit again.
    $this->drupalGet('<front>');
416
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
417 418

    // Place the "Powered by Drupal" block another time; verify a cache miss.
419
    $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered-2']);
420
    $this->drupalGet('<front>');
421
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
422 423 424

    // Verify a cache hit, but also the presence of the correct cache tags.
    $this->drupalGet('<front>');
425
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
426
    $cid_parts = [Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), ''];
427
    $cid = implode(':', $cid_parts);
428
    $cache_entry = \Drupal::cache('page')->get($cid);
429
    $expected_cache_tags = [
430
      'config:block_list',
431
      'block_view',
432 433
      'config:block.block.powered',
      'config:block.block.powered-2',
434
      'config:user.role.anonymous',
435
      'http_response',
436
      'rendered',
437
    ];
438
    sort($expected_cache_tags);
439
    $this->assertEqual($cache_entry->tags, $expected_cache_tags);
440
    $expected_cache_tags = [
441
      'block_view',
442
      'config:block.block.powered',
443
      'rendered',
444
    ];
445
    sort($expected_cache_tags);
446 447
    $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
    $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
448
    $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
449
    $expected_cache_tags = [
450
      'block_view',
451
      'config:block.block.powered-2',
452
      'rendered',
453
    ];
454
    sort($expected_cache_tags);
455 456
    $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
    $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
457 458 459 460
    $this->assertIdentical($cache_entry->tags, $expected_cache_tags);

    // Now we should have a cache hit again.
    $this->drupalGet('<front>');
461
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
462 463

    // Delete the "Powered by Drupal" blocks; verify a cache miss.
464 465 466
    $block_storage = \Drupal::entityTypeManager()->getStorage('block');
    $block_storage->load('powered')->delete();
    $block_storage->load('powered-2')->delete();
467
    $this->drupalGet('<front>');
468
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
469
  }
470 471 472 473 474 475 476 477 478 479 480 481 482 483

  /**
   * Tests that a link exists to block layout from the appearance form.
   */
  public function testThemeAdminLink() {
    $this->drupalPlaceBlock('help_block', ['region' => 'help']);
    $theme_admin = $this->drupalCreateUser([
      'administer blocks',
      'administer themes',
      'access administration pages',
    ]);
    $this->drupalLogin($theme_admin);
    $this->drupalGet('admin/appearance');
    $this->assertText('You can place blocks for each theme on the block layout page');
484
    $this->assertSession()->linkByHrefExists('admin/structure/block');
485
  }
486

487 488 489 490
  /**
   * Tests that uninstalling a theme removes its block configuration.
   */
  public function testUninstallTheme() {
491 492
    /** @var \Drupal\Core\Extension\ThemeInstallerInterface $theme_installer */
    $theme_installer = \Drupal::service('theme_installer');
493

494
    $theme_installer->install(['seven']);
495
    $this->config('system.theme')->set('default', 'seven')->save();
496 497 498 499
    $block = $this->drupalPlaceBlock('system_powered_by_block', ['theme' => 'seven', 'region' => 'help']);
    $this->drupalGet('<front>');
    $this->assertText('Powered by Drupal');

500
    $this->config('system.theme')->set('default', 'classy')->save();
501
    $theme_installer->uninstall(['seven']);
502 503 504 505 506

    // Ensure that the block configuration does not exist anymore.
    $this->assertIdentical(NULL, Block::load($block->id()));
  }

507 508 509 510 511 512 513 514 515 516 517 518 519 520
  /**
   * Tests the block access.
   */
  public function testBlockAccess() {
    $this->drupalPlaceBlock('test_access', ['region' => 'help']);

    $this->drupalGet('<front>');
    $this->assertNoText('Hello test world');

    \Drupal::state()->set('test_block_access', TRUE);
    $this->drupalGet('<front>');
    $this->assertText('Hello test world');
  }

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
  /**
   * Tests block_user_role_delete.
   */
  public function testBlockUserRoleDelete() {
    $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
    $role1->save();

    $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
    $role2->save();

    $block = Block::create([
      'id' => $this->randomMachineName(),
      'plugin' => 'system_powered_by_block',
    ]);

    $block->setVisibilityConfig('user_role', [
      'roles' => [
        $role1->id() => $role1->id(),
        $role2->id() => $role2->id(),
      ],
    ]);

    $block->save();

    $this->assertEqual($block->getVisibility()['user_role']['roles'], [
      $role1->id() => $role1->id(),
547
      $role2->id() => $role2->id(),
548 549 550 551 552 553
    ]);

    $role1->delete();

    $block = Block::load($block->id());
    $this->assertEqual($block->getVisibility()['user_role']['roles'], [
554
      $role2->id() => $role2->id(),
555 556 557
    ]);
  }

558
}