3 namespace Drupal\Tests\block\Functional\Views;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Component\Utility\Crypt;
7 use Drupal\Core\Site\Settings;
9 use Drupal\Tests\block\Functional\AssertBlockAppearsTrait;
10 use Drupal\Tests\system\Functional\Cache\AssertPageCacheContextsAndTagsTrait;
11 use Drupal\Tests\views\Functional\ViewTestBase;
12 use Drupal\views\Entity\View;
13 use Drupal\views\Views;
14 use Drupal\views\Tests\ViewTestData;
15 use Drupal\Core\Template\Attribute;
18 * Tests the block display plugin.
21 * @see \Drupal\views\Plugin\views\display\Block
23 class DisplayBlockTest extends ViewTestBase {
25 use AssertPageCacheContextsAndTagsTrait;
26 use AssertBlockAppearsTrait;
33 public static $modules = ['node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui'];
36 * Views used by this test.
40 public static $testViews = ['test_view_block', 'test_view_block2'];
45 protected function setUp($import_test_views = TRUE) {
46 parent::setUp($import_test_views);
48 ViewTestData::createTestViews(get_class($this), ['block_test_views']);
49 $this->enableViewsTestModule();
53 * Tests default and custom block categories.
55 public function testBlockCategory() {
56 $this->drupalLogin($this->drupalCreateUser(['administer views', 'administer blocks']));
58 // Create a new view in the UI.
60 $edit['label'] = $this->randomString();
61 $edit['id'] = strtolower($this->randomMachineName());
62 $edit['show[wizard_key]'] = 'standard:views_test_data';
63 $edit['description'] = $this->randomString();
64 $edit['block[create]'] = TRUE;
65 $edit['block[style][row_plugin]'] = 'fields';
66 $this->drupalPostForm('admin/structure/views/add', $edit, t('Save and edit'));
68 $pattern = '//tr[.//td[text()=:category] and .//td//a[contains(@href, :href)]]';
70 // Test that the block was given a default category corresponding to its
73 ':href' => \Drupal::Url('block.admin_add', [
74 'plugin_id' => 'views_block:' . $edit['id'] . '-block_1',
77 ':category' => 'Lists (Views)',
79 $this->drupalGet('admin/structure/block');
80 $this->clickLink('Place block');
81 $elements = $this->xpath($pattern, $arguments);
82 $this->assertTrue(!empty($elements), 'The test block appears in the category for its base table.');
84 // Duplicate the block before changing the category.
85 $this->drupalPostForm('admin/structure/views/view/' . $edit['id'] . '/edit/block_1', [], t('Duplicate @display_title', ['@display_title' => 'Block']));
86 $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_2');
88 // Change the block category to a random string.
89 $this->drupalGet('admin/structure/views/view/' . $edit['id'] . '/edit/block_1');
90 $link = $this->xpath('//a[@id="views-block-1-block-category" and normalize-space(text())=:category]', $arguments);
91 $this->assertTrue(!empty($link));
92 $this->clickLink(t('Lists (Views)'));
93 $category = $this->randomString();
94 $this->drupalPostForm(NULL, ['block_category' => $category], t('Apply'));
96 // Duplicate the block after changing the category.
97 $this->drupalPostForm(NULL, [], t('Duplicate @display_title', ['@display_title' => 'Block']));
98 $this->assertUrl('admin/structure/views/view/' . $edit['id'] . '/edit/block_3');
100 $this->drupalPostForm(NULL, [], t('Save'));
102 // Test that the blocks are listed under the correct categories.
103 $arguments[':category'] = $category;
104 $this->drupalGet('admin/structure/block');
105 $this->clickLink('Place block');
106 $elements = $this->xpath($pattern, $arguments);
107 $this->assertTrue(!empty($elements), 'The test block appears in the custom category.');
110 ':href' => \Drupal::Url('block.admin_add', [
111 'plugin_id' => 'views_block:' . $edit['id'] . '-block_2',
114 ':category' => 'Lists (Views)',
116 $elements = $this->xpath($pattern, $arguments);
117 $this->assertTrue(!empty($elements), 'The first duplicated test block remains in the original category.');
120 ':href' => \Drupal::Url('block.admin_add', [
121 'plugin_id' => 'views_block:' . $edit['id'] . '-block_3',
124 ':category' => $category,
126 $elements = $this->xpath($pattern, $arguments);
127 $this->assertTrue(!empty($elements), 'The second duplicated test block appears in the custom category.');
131 * Tests removing a block display.
133 public function testDeleteBlockDisplay() {
134 // To test all combinations possible we first place create two instances
135 // of the block display of the first view.
136 $block_1 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1']);
137 $block_2 = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:2']);
139 // Then we add one instance of blocks for each of the two displays of the
141 $block_3 = $this->drupalPlaceBlock('views_block:test_view_block2-block_1', ['label' => 'test_view_block2-block_1']);
142 $block_4 = $this->drupalPlaceBlock('views_block:test_view_block2-block_2', ['label' => 'test_view_block2-block_2']);
144 $this->drupalGet('test-page');
145 $this->assertBlockAppears($block_1);
146 $this->assertBlockAppears($block_2);
147 $this->assertBlockAppears($block_3);
148 $this->assertBlockAppears($block_4);
150 $block_storage = $this->container->get('entity_type.manager')->getStorage('block');
152 // Remove the block display, so both block entities from the first view
153 // should both disappear.
154 $view = Views::getView('test_view_block');
155 $view->initDisplay();
156 $view->displayHandlers->remove('block_1');
157 $view->storage->save();
159 $this->assertFalse($block_storage->load($block_1->id()), 'The block for this display was removed.');
160 $this->assertFalse($block_storage->load($block_2->id()), 'The block for this display was removed.');
161 $this->assertTrue($block_storage->load($block_3->id()), 'A block from another view was unaffected.');
162 $this->assertTrue($block_storage->load($block_4->id()), 'A block from another view was unaffected.');
163 $this->drupalGet('test-page');
164 $this->assertNoBlockAppears($block_1);
165 $this->assertNoBlockAppears($block_2);
166 $this->assertBlockAppears($block_3);
167 $this->assertBlockAppears($block_4);
169 // Remove the first block display of the second view and ensure the block
170 // instance of the second block display still exists.
171 $view = Views::getView('test_view_block2');
172 $view->initDisplay();
173 $view->displayHandlers->remove('block_1');
174 $view->storage->save();
176 $this->assertFalse($block_storage->load($block_3->id()), 'The block for this display was removed.');
177 $this->assertTrue($block_storage->load($block_4->id()), 'A block from another display on the same view was unaffected.');
178 $this->drupalGet('test-page');
179 $this->assertNoBlockAppears($block_3);
180 $this->assertBlockAppears($block_4);
184 * Test the block form for a Views block.
186 public function testViewsBlockForm() {
187 $this->drupalLogin($this->drupalCreateUser(['administer blocks']));
188 $default_theme = $this->config('system.theme')->get('default');
189 $this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
190 $elements = $this->xpath('//input[@name="label"]');
191 $this->assertTrue(empty($elements), 'The label field is not found for Views blocks.');
192 // Test that that machine name field is hidden from display and has been
193 // saved as expected from the default value.
194 $this->assertNoFieldById('edit-machine-name', 'views_block__test_view_block_1', 'The machine name is hidden on the views block form.');
197 $edit = ['region' => 'content'];
198 $this->drupalPostForm(NULL, $edit, t('Save block'));
199 $storage = $this->container->get('entity_type.manager')->getStorage('block');
200 $block = $storage->load('views_block__test_view_block_block_1');
201 // This will only return a result if our new block has been created with the
202 // expected machine name.
203 $this->assertTrue(!empty($block), 'The expected block was loaded.');
205 for ($i = 2; $i <= 3; $i++) {
206 // Place the same block again and make sure we have a new ID.
207 $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
208 $block = $storage->load('views_block__test_view_block_block_1_' . $i);
209 // This will only return a result if our new block has been created with the
210 // expected machine name.
211 $this->assertTrue(!empty($block), 'The expected block was loaded.');
214 // Tests the override capability of items per page.
215 $this->drupalGet('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme);
216 $edit = ['region' => 'content'];
217 $edit['settings[override][items_per_page]'] = 10;
219 $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
221 $block = $storage->load('views_block__test_view_block_block_1_4');
222 $config = $block->getPlugin()->getConfiguration();
223 $this->assertEqual(10, $config['items_per_page'], "'Items per page' is properly saved.");
225 $edit['settings[override][items_per_page]'] = 5;
226 $this->drupalPostForm('admin/structure/block/manage/views_block__test_view_block_block_1_4', $edit, t('Save block'));
228 $block = $storage->load('views_block__test_view_block_block_1_4');
230 $config = $block->getPlugin()->getConfiguration();
231 $this->assertEqual(5, $config['items_per_page'], "'Items per page' is properly saved.");
233 // Tests the override of the label capability.
234 $edit = ['region' => 'content'];
235 $edit['settings[views_label_checkbox]'] = 1;
236 $edit['settings[views_label]'] = 'Custom title';
237 $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
239 $block = $storage->load('views_block__test_view_block_block_1_5');
240 $config = $block->getPlugin()->getConfiguration();
241 $this->assertEqual('Custom title', $config['views_label'], "'Label' is properly saved.");
245 * Tests the actual rendering of the views block.
247 public function testBlockRendering() {
248 // Create a block and set a custom title.
249 $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
250 $this->drupalGet('');
252 $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
253 $this->assertEqual($result[0]->getText(), 'Custom title');
255 // Don't override the title anymore.
256 $plugin = $block->getPlugin();
257 $plugin->setConfigurationValue('views_label', '');
260 $this->drupalGet('');
261 $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
262 $this->assertEqual($result[0]->getText(), 'test_view_block');
265 $block->getPlugin()->setConfigurationValue('label_display', FALSE);
268 $this->drupalGet('');
269 $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
270 $this->assertTrue(empty($result), 'The title is not visible.');
272 $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:system.site', 'config:views.view.test_view_block', 'http_response', 'rendered']));
276 * Tests the various testcases of empty block rendering.
278 public function testBlockEmptyRendering() {
279 $url = new Url('test_page_test.test_page');
280 // Remove all views_test_data entries.
281 \Drupal::database()->truncate('views_test_data')->execute();
282 /** @var \Drupal\views\ViewEntityInterface $view */
283 $view = View::load('test_view_block');
284 $view->invalidateCaches();
286 $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1', ['label' => 'test_view_block-block_1:1', 'views_label' => 'Custom title']);
287 $this->drupalGet('');
288 $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
290 $display = &$view->getDisplay('block_1');
291 $display['display_options']['block_hide_empty'] = TRUE;
294 $this->drupalGet($url);
295 $this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
296 // Ensure that the view cacheability metadata is propagated even, for an
298 $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
299 $this->assertCacheContexts(['url.query_args:_wrapper_format']);
301 // Add a header displayed on empty result.
302 $display = &$view->getDisplay('block_1');
303 $display['display_options']['defaults']['header'] = FALSE;
304 $display['display_options']['header']['example'] = [
305 'field' => 'area_text_custom',
306 'id' => 'area_text_custom',
308 'plugin_id' => 'text_custom',
309 'content' => 'test header',
314 $this->drupalGet($url);
315 $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
316 $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
317 $this->assertCacheContexts(['url.query_args:_wrapper_format']);
319 // Hide the header on empty results.
320 $display = &$view->getDisplay('block_1');
321 $display['display_options']['defaults']['header'] = FALSE;
322 $display['display_options']['header']['example'] = [
323 'field' => 'area_text_custom',
324 'id' => 'area_text_custom',
326 'plugin_id' => 'text_custom',
327 'content' => 'test header',
332 $this->drupalGet($url);
333 $this->assertEqual(0, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
334 $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
335 $this->assertCacheContexts(['url.query_args:_wrapper_format']);
337 // Add an empty text.
338 $display = &$view->getDisplay('block_1');
339 $display['display_options']['defaults']['empty'] = FALSE;
340 $display['display_options']['empty']['example'] = [
341 'field' => 'area_text_custom',
342 'id' => 'area_text_custom',
344 'plugin_id' => 'text_custom',
345 'content' => 'test empty',
349 $this->drupalGet($url);
350 $this->assertEqual(1, count($this->xpath('//div[contains(@class, "block-views-blocktest-view-block-block-1")]')));
351 $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
352 $this->assertCacheContexts(['url.query_args:_wrapper_format']);
356 * Tests the contextual links on a Views block.
358 public function testBlockContextualLinks() {
359 $this->drupalLogin($this->drupalCreateUser(['administer views', 'access contextual links', 'administer blocks']));
360 $block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
361 $cached_block = $this->drupalPlaceBlock('views_block:test_view_block-block_1');
362 $this->drupalGet('test-page');
364 $id = 'block:block=' . $block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
365 $id_token = Crypt::hmacBase64($id, Settings::getHashSalt() . $this->container->get('private_key')->get());
366 $cached_id = 'block:block=' . $cached_block->id() . ':langcode=en|entity.view.edit_form:view=test_view_block:location=block&name=test_view_block&display_id=block_1&langcode=en';
367 $cached_id_token = Crypt::hmacBase64($cached_id, Settings::getHashSalt() . $this->container->get('private_key')->get());
368 // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:assertContextualLinkPlaceHolder()
369 $this->assertRaw('<div' . new Attribute(['data-contextual-id' => $id, 'data-contextual-token' => $id_token]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $id]));
370 $this->assertRaw('<div' . new Attribute(['data-contextual-id' => $cached_id, 'data-contextual-token' => $cached_id_token]) . '></div>', format_string('Contextual link placeholder with id @id exists.', ['@id' => $cached_id]));
372 // Get server-rendered contextual links.
373 // @see \Drupal\contextual\Tests\ContextualDynamicContextTest:renderContextualLinks()
374 $post = ['ids[0]' => $id, 'ids[1]' => $cached_id, 'tokens[0]' => $id_token, 'tokens[1]' => $cached_id_token];
375 $url = 'contextual/render?_format=json,destination=test-page';
376 $this->getSession()->getDriver()->getClient()->request('POST', $url, $post);
377 $this->assertResponse(200);
378 $json = Json::decode($this->getSession()->getPage()->getContent());
379 $this->assertIdentical($json[$id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');
380 $this->assertIdentical($json[$cached_id], '<ul class="contextual-links"><li class="block-configure"><a href="' . base_path() . 'admin/structure/block/manage/' . $cached_block->id() . '">Configure block</a></li><li class="entityviewedit-form"><a href="' . base_path() . 'admin/structure/views/view/test_view_block/edit/block_1">Edit view</a></li></ul>');