Pull merge.
[yaffs-website] / web / core / modules / block / tests / src / Functional / BlockTest.php
1 <?php
2
3 namespace Drupal\Tests\block\Functional;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\block\Entity\Block;
7 use Drupal\Core\Url;
8 use Drupal\user\Entity\Role;
9 use Drupal\user\RoleInterface;
10
11 /**
12  * Tests basic block functionality.
13  *
14  * @group block
15  */
16 class BlockTest extends BlockTestBase {
17
18   /**
19    * Tests block visibility.
20    */
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');
27     $edit = [
28       'id' => strtolower($this->randomMachineName(8)),
29       'region' => 'sidebar_first',
30       'settings[label]' => $title,
31       'settings[label_display]' => TRUE,
32     ];
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');
40
41     $this->drupalPostForm(NULL, $edit, t('Save block'));
42     $this->assertText('The block configuration has been saved.', 'Block was saved');
43
44     $this->clickLink('Configure');
45     $this->assertFieldChecked('edit-visibility-request-path-negate-1');
46
47     $this->drupalGet('');
48     $this->assertText($title, 'Block was displayed on the front page.');
49
50     $this->drupalGet('user');
51     $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
52
53     // Confirm that the block is not displayed to anonymous users.
54     $this->drupalLogout();
55     $this->drupalGet('');
56     $this->assertNoText($title, 'Block was not displayed to anonymous users.');
57
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.');
61   }
62
63   /**
64    * Tests that visibility can be properly toggled.
65    */
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');
72     $edit = [
73       'id' => strtolower($this->randomMachineName(8)),
74       'region' => 'sidebar_first',
75       'settings[label]' => $title,
76     ];
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');
83
84     $edit = [
85       'visibility[user_role][roles][' . RoleInterface::AUTHENTICATED_ID . ']' => FALSE,
86     ];
87     $this->drupalPostForm(NULL, $edit, 'Save block');
88     $this->clickLink('Configure');
89     $this->assertNoFieldChecked('edit-visibility-user-role-roles-authenticated');
90
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'));
97   }
98
99   /**
100    * Test block visibility when leaving "pages" textarea empty.
101    */
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');
108     $edit = [
109       'id' => strtolower($this->randomMachineName(8)),
110       'region' => 'sidebar_first',
111       'settings[label]' => $title,
112       'visibility[request_path][negate]' => TRUE,
113     ];
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');
118
119     $this->drupalGet('user');
120     $this->assertNoText($title, 'Block was not displayed according to block visibility rules.');
121
122     $this->drupalGet('USER');
123     $this->assertNoText($title, 'Block was not displayed according to block visibility rules regardless of path case.');
124
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.');
129   }
130
131   /**
132    * Tests adding a block from the library page with a weight query string.
133    */
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) {
138       $options = [
139         'query' => [
140           'region' => 'sidebar_first',
141           'weight' => $weight,
142         ],
143       ];
144       $this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme], $options));
145
146       $block_name = 'system_powered_by_block';
147       $add_url = Url::fromRoute('block.admin_add', [
148         'plugin_id' => $block_name,
149         'theme' => $default_theme,
150       ]);
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.');
154
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.');
158
159       // Create a random title for the block.
160       $title = $this->randomMachineName(8);
161       $block_id = strtolower($this->randomMachineName(8));
162       $edit = [
163         'id' => $block_id,
164         'settings[label]' => $title,
165       ];
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'));
168
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.');
173     }
174   }
175
176   /**
177    * Test configuring and moving a module-define block to specific regions.
178    */
179   public function testBlock() {
180     // Place page title block to test error messages.
181     $this->drupalPlaceBlock('page_title_block');
182
183     // Disable the block.
184     $this->drupalGet('admin/structure/block');
185     $this->clickLink('Disable');
186
187     // Select the 'Powered by Drupal' block to be configured and moved.
188     $block = [];
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';
194
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']);
200
201     $this->assertEqual($instance->label(), $block['settings[label]'], 'Stored block title found.');
202
203     // Check whether the block can be moved to all available regions.
204     foreach ($this->regions as $region) {
205       $this->moveBlockToRegion($block, $region);
206     }
207
208     // Disable the block.
209     $this->drupalGet('admin/structure/block');
210     $this->clickLink('Disable');
211
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.');
214
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.');
222
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]']]));
229
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());
239   }
240
241   /**
242    * Tests the block operation links.
243    */
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');
252
253     $url = $this->getUrl();
254     $parsed = parse_url($url);
255     $this->assertContains('block-placement', $parsed['query']);
256
257     $this->clickLink('Remove');
258     $this->submitForm([], 'Remove');
259
260     $url = $this->getUrl();
261     $parsed = parse_url($url);
262     $this->assertTrue(empty($parsed['query']));
263   }
264
265   /**
266    * Tests that the block form has a theme selector when not passed via the URL.
267    */
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.
276       $block = [];
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']));
283
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.');
289     }
290   }
291
292   /**
293    * Test block display of theme titles.
294    */
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\'>)');
307   }
308
309   /**
310    * Test block title display settings.
311    */
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');
319     $edit = [
320       'id' => $id,
321       'region' => 'sidebar_first',
322       'settings[label]' => $title,
323     ];
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');
326
327     $this->drupalGet('user');
328     $this->assertNoText($title, 'Block title was not displayed by default.');
329
330     $edit = [
331       'settings[label_display]' => TRUE,
332     ];
333     $this->drupalPostForm('admin/structure/block/manage/' . $id, $edit, t('Save block'));
334     $this->assertText('The block configuration has been saved.', 'Block was saved');
335
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.');
338
339     $this->drupalGet('user');
340     $this->assertText($title, 'Block title was displayed when enabled.');
341   }
342
343   /**
344    * Moves a block to a given region via the UI and confirms the result.
345    *
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'.
354    */
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')];
358     $edit = [];
359     $edit['blocks[' . $block['id'] . '][region]'] = $region;
360     $this->drupalPostForm('admin/structure/block', $edit, t('Save blocks'));
361
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]));
364
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.');
368
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'])),
373     ]);
374     $this->assertFieldByXPath($xpath, NULL, t('Block found in %region_name region.', ['%region_name' => Html::getClass($region)]));
375   }
376
377   /**
378    * Test that cache tags are properly set and bubbled up to the page cache.
379    *
380    * Verify that invalidation of these cache tags works:
381    * - "block:<block ID>"
382    * - "block_plugin:<block plugin ID>"
383    */
384   public function testBlockCacheTags() {
385     // The page cache only works for anonymous users.
386     $this->drupalLogout();
387
388     // Enable page caching.
389     $config = $this->config('system.performance');
390     $config->set('cache.page.max_age', 300);
391     $config->save();
392
393     // Place the "Powered by Drupal" block.
394     $block = $this->drupalPlaceBlock('system_powered_by_block', ['id' => 'powered']);
395
396     // Prime the page cache.
397     $this->drupalGet('<front>');
398     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
399
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 = [
408       'config:block_list',
409       'block_view',
410       'config:block.block.powered',
411       'config:user.role.anonymous',
412       'http_response',
413       'rendered',
414     ];
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 = [
420       'block_view',
421       'config:block.block.powered',
422       'rendered',
423     ];
424     sort($expected_cache_tags);
425     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
426
427     // The "Powered by Drupal" block is modified; verify a cache miss.
428     $block->setRegion('content');
429     $block->save();
430     $this->drupalGet('<front>');
431     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
432
433     // Now we should have a cache hit again.
434     $this->drupalGet('<front>');
435     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
436
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');
441
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 = [
449       'config:block_list',
450       'block_view',
451       'config:block.block.powered',
452       'config:block.block.powered-2',
453       'config:user.role.anonymous',
454       'http_response',
455       'rendered',
456     ];
457     sort($expected_cache_tags);
458     $this->assertEqual($cache_entry->tags, $expected_cache_tags);
459     $expected_cache_tags = [
460       'block_view',
461       'config:block.block.powered',
462       'rendered',
463     ];
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 = [
469       'block_view',
470       'config:block.block.powered-2',
471       'rendered',
472     ];
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);
477
478     // Now we should have a cache hit again.
479     $this->drupalGet('<front>');
480     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
481
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');
486   }
487
488   /**
489    * Tests that a link exists to block layout from the appearance form.
490    */
491   public function testThemeAdminLink() {
492     $this->drupalPlaceBlock('help_block', ['region' => 'help']);
493     $theme_admin = $this->drupalCreateUser([
494       'administer blocks',
495       'administer themes',
496       'access administration pages',
497     ]);
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');
502   }
503
504   /**
505    * Tests that uninstalling a theme removes its block configuration.
506    */
507   public function testUninstallTheme() {
508     /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
509     $theme_handler = \Drupal::service('theme_handler');
510
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');
516
517     $this->config('system.theme')->set('default', 'classy')->save();
518     $theme_handler->uninstall(['seven']);
519
520     // Ensure that the block configuration does not exist anymore.
521     $this->assertIdentical(NULL, Block::load($block->id()));
522   }
523
524   /**
525    * Tests the block access.
526    */
527   public function testBlockAccess() {
528     $this->drupalPlaceBlock('test_access', ['region' => 'help']);
529
530     $this->drupalGet('<front>');
531     $this->assertNoText('Hello test world');
532
533     \Drupal::state()->set('test_block_access', TRUE);
534     $this->drupalGet('<front>');
535     $this->assertText('Hello test world');
536   }
537
538   /**
539    * Tests block_user_role_delete.
540    */
541   public function testBlockUserRoleDelete() {
542     $role1 = Role::create(['id' => 'test_role1', 'name' => $this->randomString()]);
543     $role1->save();
544
545     $role2 = Role::create(['id' => 'test_role2', 'name' => $this->randomString()]);
546     $role2->save();
547
548     $block = Block::create([
549       'id' => $this->randomMachineName(),
550       'plugin' => 'system_powered_by_block',
551     ]);
552
553     $block->setVisibilityConfig('user_role', [
554       'roles' => [
555         $role1->id() => $role1->id(),
556         $role2->id() => $role2->id(),
557       ],
558     ]);
559
560     $block->save();
561
562     $this->assertEqual($block->getVisibility()['user_role']['roles'], [
563       $role1->id() => $role1->id(),
564       $role2->id() => $role2->id(),
565     ]);
566
567     $role1->delete();
568
569     $block = Block::load($block->id());
570     $this->assertEqual($block->getVisibility()['user_role']['roles'], [
571       $role2->id() => $role2->id(),
572     ]);
573   }
574
575 }