Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / modules / block / tests / src / Functional / Views / DisplayBlockTest.php
1 <?php
2
3 namespace Drupal\Tests\block\Functional\Views;
4
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Component\Utility\Crypt;
7 use Drupal\Core\Site\Settings;
8 use Drupal\Core\Url;
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;
16
17 /**
18  * Tests the block display plugin.
19  *
20  * @group block
21  * @see \Drupal\views\Plugin\views\display\Block
22  */
23 class DisplayBlockTest extends ViewTestBase {
24
25   use AssertPageCacheContextsAndTagsTrait;
26   use AssertBlockAppearsTrait;
27
28   /**
29    * Modules to install.
30    *
31    * @var array
32    */
33   public static $modules = ['node', 'block_test_views', 'test_page_test', 'contextual', 'views_ui'];
34
35   /**
36    * Views used by this test.
37    *
38    * @var array
39    */
40   public static $testViews = ['test_view_block', 'test_view_block2'];
41
42   /**
43    * {@inheritdoc}
44    */
45   protected function setUp($import_test_views = TRUE) {
46     parent::setUp($import_test_views);
47
48     ViewTestData::createTestViews(get_class($this), ['block_test_views']);
49     $this->enableViewsTestModule();
50   }
51
52   /**
53    * Tests default and custom block categories.
54    */
55   public function testBlockCategory() {
56     $this->drupalLogin($this->drupalCreateUser(['administer views', 'administer blocks']));
57
58     // Create a new view in the UI.
59     $edit = [];
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'));
67
68     $pattern = '//tr[.//td[text()=:category] and .//td//a[contains(@href, :href)]]';
69
70     // Test that the block was given a default category corresponding to its
71     // base table.
72     $arguments = [
73       ':href' => \Drupal::Url('block.admin_add', [
74         'plugin_id' => 'views_block:' . $edit['id'] . '-block_1',
75         'theme' => 'classy',
76       ]),
77       ':category' => 'Lists (Views)',
78     ];
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.');
83
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');
87
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'));
95
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');
99
100     $this->drupalPostForm(NULL, [], t('Save'));
101
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.');
108
109     $arguments = [
110       ':href' => \Drupal::Url('block.admin_add', [
111         'plugin_id' => 'views_block:' . $edit['id'] . '-block_2',
112         'theme' => 'classy',
113       ]),
114       ':category' => 'Lists (Views)',
115     ];
116     $elements = $this->xpath($pattern, $arguments);
117     $this->assertTrue(!empty($elements), 'The first duplicated test block remains in the original category.');
118
119     $arguments = [
120       ':href' => \Drupal::Url('block.admin_add', [
121         'plugin_id' => 'views_block:' . $edit['id'] . '-block_3',
122         'theme' => 'classy',
123       ]),
124       ':category' => $category,
125     ];
126     $elements = $this->xpath($pattern, $arguments);
127     $this->assertTrue(!empty($elements), 'The second duplicated test block appears in the custom category.');
128   }
129
130   /**
131    * Tests removing a block display.
132    */
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']);
138
139     // Then we add one instance of blocks for each of the two displays of the
140     // second view.
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']);
143
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);
149
150     $block_storage = $this->container->get('entity_type.manager')->getStorage('block');
151
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();
158
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);
168
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();
175
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);
181   }
182
183   /**
184    * Test the block form for a Views block.
185    */
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.');
195
196     // Save the block.
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.');
204
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.');
212     }
213
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;
218
219     $this->drupalPostForm('admin/structure/block/add/views_block:test_view_block-block_1/' . $default_theme, $edit, t('Save block'));
220
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.");
224
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'));
227
228     $block = $storage->load('views_block__test_view_block_block_1_4');
229
230     $config = $block->getPlugin()->getConfiguration();
231     $this->assertEqual(5, $config['items_per_page'], "'Items per page' is properly saved.");
232
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'));
238
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.");
242   }
243
244   /**
245    * Tests the actual rendering of the views block.
246    */
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('');
251
252     $result = $this->xpath('//div[contains(@class, "region-sidebar-first")]/div[contains(@class, "block-views")]/h2');
253     $this->assertEqual($result[0]->getText(), 'Custom title');
254
255     // Don't override the title anymore.
256     $plugin = $block->getPlugin();
257     $plugin->setConfigurationValue('views_label', '');
258     $block->save();
259
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');
263
264     // Hide the title.
265     $block->getPlugin()->setConfigurationValue('label_display', FALSE);
266     $block->save();
267
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.');
271
272     $this->assertCacheTags(array_merge($block->getCacheTags(), ['block_view', 'config:block_list', 'config:system.site', 'config:views.view.test_view_block', 'http_response', 'rendered']));
273   }
274
275   /**
276    * Tests the various testcases of empty block rendering.
277    */
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();
285
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")]')));
289
290     $display = &$view->getDisplay('block_1');
291     $display['display_options']['block_hide_empty'] = TRUE;
292     $view->save();
293
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
297     // empty block.
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']);
300
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',
307       'table' => 'views',
308       'plugin_id' => 'text_custom',
309       'content' => 'test header',
310       'empty' => TRUE,
311     ];
312     $view->save();
313
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']);
318
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',
325       'table' => 'views',
326       'plugin_id' => 'text_custom',
327       'content' => 'test header',
328       'empty' => FALSE,
329     ];
330     $view->save();
331
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']);
336
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',
343       'table' => 'views',
344       'plugin_id' => 'text_custom',
345       'content' => 'test empty',
346     ];
347     $view->save();
348
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']);
353   }
354
355   /**
356    * Tests the contextual links on a Views block.
357    */
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');
363
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]));
371
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>');
381   }
382
383 }