Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / views / tests / src / Kernel / ViewExecutableTest.php
1 <?php
2
3 namespace Drupal\Tests\views\Kernel;
4
5 use Drupal\comment\Tests\CommentTestTrait;
6 use Drupal\Component\Utility\Xss;
7 use Drupal\node\Entity\NodeType;
8 use Drupal\views\Entity\View;
9 use Drupal\views\Views;
10 use Drupal\views\ViewExecutable;
11 use Drupal\views\ViewExecutableFactory;
12 use Drupal\views\DisplayPluginCollection;
13 use Drupal\views\Plugin\views\display\DefaultDisplay;
14 use Drupal\views\Plugin\views\display\Page;
15 use Drupal\views\Plugin\views\style\DefaultStyle;
16 use Drupal\views\Plugin\views\style\Grid;
17 use Drupal\views\Plugin\views\row\Fields;
18 use Drupal\views\Plugin\views\query\Sql;
19 use Drupal\views\Plugin\views\pager\PagerPluginBase;
20 use Drupal\views\Plugin\views\query\QueryPluginBase;
21 use Drupal\views_test_data\Plugin\views\display\DisplayTest;
22 use Symfony\Component\HttpFoundation\Response;
23
24 /**
25  * Tests the ViewExecutable class.
26  *
27  * @group views
28  * @see \Drupal\views\ViewExecutable
29  */
30 class ViewExecutableTest extends ViewsKernelTestBase {
31
32   use CommentTestTrait;
33
34   public static $modules = ['system', 'node', 'comment', 'user', 'filter', 'field', 'text'];
35
36   /**
37    * Views used by this test.
38    *
39    * @var array
40    */
41   public static $testViews = ['test_destroy', 'test_executable_displays', 'test_argument_dependency'];
42
43   /**
44    * Properties that should be stored in the configuration.
45    *
46    * @var array
47    */
48   protected $configProperties = [
49     'disabled',
50     'name',
51     'description',
52     'tag',
53     'base_table',
54     'label',
55     'core',
56     'display',
57   ];
58
59   /**
60    * Properties that should be stored in the executable.
61    *
62    * @var array
63    */
64   protected $executableProperties = [
65     'storage',
66     'built',
67     'executed',
68     'args',
69     'build_info',
70     'result',
71     'attachment_before',
72     'attachment_after',
73     'exposed_data',
74     'exposed_raw_input',
75     'old_view',
76     'parent_views',
77   ];
78
79   protected function setUpFixtures() {
80     $this->installEntitySchema('user');
81     $this->installEntitySchema('node');
82     $this->installEntitySchema('comment');
83     $this->installSchema('comment', ['comment_entity_statistics']);
84     $this->installConfig(['system', 'field', 'node', 'comment']);
85
86     NodeType::create([
87       'type' => 'page',
88       'name' => 'Page',
89     ])->save();
90     $this->addDefaultCommentField('node', 'page');
91     parent::setUpFixtures();
92
93     $this->installConfig(['filter']);
94   }
95
96   /**
97    * Tests the views.executable container service.
98    */
99   public function testFactoryService() {
100     $factory = $this->container->get('views.executable');
101     $this->assertTrue($factory instanceof ViewExecutableFactory, 'A ViewExecutableFactory instance was returned from the container.');
102     $view = View::load('test_executable_displays');
103     $this->assertTrue($factory->get($view) instanceof ViewExecutable, 'A ViewExecutable instance was returned from the factory.');
104   }
105
106   /**
107    * Tests the initDisplay() and initHandlers() methods.
108    */
109   public function testInitMethods() {
110     $view = Views::getView('test_destroy');
111     $view->initDisplay();
112
113     $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'Make sure a reference to the current display handler is set.');
114     $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay, 'Make sure a display handler is created for each display.');
115
116     $view->destroy();
117     $view->initHandlers();
118
119     // Check for all handler types.
120     $handler_types = array_keys(ViewExecutable::getHandlerTypes());
121     foreach ($handler_types as $type) {
122       // The views_test integration doesn't have relationships.
123       if ($type == 'relationship') {
124         continue;
125       }
126       $this->assertTrue(count($view->$type), format_string('Make sure a %type instance got instantiated.', ['%type' => $type]));
127     }
128
129     // initHandlers() should create display handlers automatically as well.
130     $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'Make sure a reference to the current display handler is set.');
131     $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay, 'Make sure a display handler is created for each display.');
132
133     $view_hash = spl_object_hash($view);
134     $display_hash = spl_object_hash($view->display_handler);
135
136     // Test the initStyle() method.
137     $view->initStyle();
138     $this->assertTrue($view->style_plugin instanceof DefaultStyle, 'Make sure a reference to the style plugin is set.');
139     // Test the plugin has been invited and view have references to the view and
140     // display handler.
141     $this->assertEqual(spl_object_hash($view->style_plugin->view), $view_hash);
142     $this->assertEqual(spl_object_hash($view->style_plugin->displayHandler), $display_hash);
143
144     // Test the initQuery method().
145     $view->initQuery();
146     $this->assertTrue($view->query instanceof Sql, 'Make sure a reference to the query is set');
147     $this->assertEqual(spl_object_hash($view->query->view), $view_hash);
148     $this->assertEqual(spl_object_hash($view->query->displayHandler), $display_hash);
149
150     $view->destroy();
151
152     // Test the plugin  get methods.
153     $display_plugin = $view->getDisplay();
154     $this->assertTrue($display_plugin instanceof DefaultDisplay, 'An instance of DefaultDisplay was returned.');
155     $this->assertTrue($view->display_handler instanceof DefaultDisplay, 'The display_handler property has been set.');
156     $this->assertIdentical($display_plugin, $view->getDisplay(), 'The same display plugin instance was returned.');
157
158     $style_plugin = $view->getStyle();
159     $this->assertTrue($style_plugin instanceof DefaultStyle, 'An instance of DefaultStyle was returned.');
160     $this->assertTrue($view->style_plugin instanceof DefaultStyle, 'The style_plugin property has been set.');
161     $this->assertIdentical($style_plugin, $view->getStyle(), 'The same style plugin instance was returned.');
162
163     $pager_plugin = $view->getPager();
164     $this->assertTrue($pager_plugin instanceof PagerPluginBase, 'An instance of PagerPluginBase was returned.');
165     $this->assertTrue($view->pager instanceof PagerPluginBase, 'The pager property has been set.');
166     $this->assertIdentical($pager_plugin, $view->getPager(), 'The same pager plugin instance was returned.');
167
168     $query_plugin = $view->getQuery();
169     $this->assertTrue($query_plugin instanceof QueryPluginBase, 'An instance of QueryPluginBase was returned.');
170     $this->assertTrue($view->query instanceof QueryPluginBase, 'The query property has been set.');
171     $this->assertIdentical($query_plugin, $view->getQuery(), 'The same query plugin instance was returned.');
172   }
173
174   /**
175    * Tests the generation of the executable object.
176    */
177   public function testConstructing() {
178     Views::getView('test_destroy');
179   }
180
181   /**
182    * Tests the accessing of values on the object.
183    */
184   public function testProperties() {
185     $view = Views::getView('test_destroy');
186     foreach ($this->executableProperties as $property) {
187       $this->assertTrue(isset($view->{$property}));
188     }
189
190     // Per default exposed input should fall back to an empty array.
191     $this->assertEqual($view->getExposedInput(), []);
192   }
193
194   public function testSetDisplayWithInvalidDisplay() {
195     $view = Views::getView('test_executable_displays');
196     $view->initDisplay();
197
198     // Error is triggered while calling the wrong display.
199     try {
200       $view->setDisplay('invalid');
201       $this->fail('Expected error, when setDisplay() called with invalid display ID');
202     }
203     catch (\PHPUnit_Framework_Error_Warning $e) {
204       $this->assertEquals('setDisplay() called with invalid display ID "invalid".', $e->getMessage());
205     }
206
207     $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with an invalid display id the default display should be used.');
208     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
209   }
210
211   /**
212    * Tests the display related methods and properties.
213    */
214   public function testDisplays() {
215     $view = Views::getView('test_executable_displays');
216
217     // Tests Drupal\views\ViewExecutable::initDisplay().
218     $view->initDisplay();
219     $this->assertTrue($view->displayHandlers instanceof DisplayPluginCollection, 'The displayHandlers property has the right class.');
220     // Tests the classes of the instances.
221     $this->assertTrue($view->displayHandlers->get('default') instanceof DefaultDisplay);
222     $this->assertTrue($view->displayHandlers->get('page_1') instanceof Page);
223     $this->assertTrue($view->displayHandlers->get('page_2') instanceof Page);
224
225     // After initializing the default display is the current used display.
226     $this->assertEqual($view->current_display, 'default');
227     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
228
229     // All handlers should have a reference to the default display.
230     $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_1')->default_display), spl_object_hash($view->displayHandlers->get('default')));
231     $this->assertEqual(spl_object_hash($view->displayHandlers->get('page_2')->default_display), spl_object_hash($view->displayHandlers->get('default')));
232
233     // Tests Drupal\views\ViewExecutable::setDisplay().
234     $view->setDisplay();
235     $this->assertEqual($view->current_display, 'default', 'If setDisplay is called with no parameter the default display should be used.');
236     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('default')));
237
238     // Set two different valid displays.
239     $view->setDisplay('page_1');
240     $this->assertEqual($view->current_display, 'page_1', 'If setDisplay is called with a valid display id the appropriate display should be used.');
241     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_1')));
242
243     $view->setDisplay('page_2');
244     $this->assertEqual($view->current_display, 'page_2', 'If setDisplay is called with a valid display id the appropriate display should be used.');
245     $this->assertEqual(spl_object_hash($view->display_handler), spl_object_hash($view->displayHandlers->get('page_2')));
246
247     // Destroy the view, so we can start again and test an invalid display.
248     $view->destroy();
249
250     // Test the style and row plugins are replaced correctly when setting the
251     // display.
252     $view->setDisplay('page_1');
253     $view->initStyle();
254     $this->assertTrue($view->style_plugin instanceof DefaultStyle);
255     $this->assertTrue($view->rowPlugin instanceof Fields);
256
257     $view->setDisplay('page_2');
258     $view->initStyle();
259     $this->assertTrue($view->style_plugin instanceof Grid);
260     // @todo Change this rowPlugin type too.
261     $this->assertTrue($view->rowPlugin instanceof Fields);
262
263     // Test the newDisplay() method.
264     $view = $this->container->get('entity.manager')->getStorage('view')->create(['id' => 'test_executable_displays']);
265     $executable = $view->getExecutable();
266
267     $executable->newDisplay('page');
268     $executable->newDisplay('page');
269     $executable->newDisplay('display_test');
270
271     $this->assertTrue($executable->displayHandlers->get('default') instanceof DefaultDisplay);
272     $this->assertFalse(isset($executable->displayHandlers->get('default')->default_display));
273     $this->assertTrue($executable->displayHandlers->get('page_1') instanceof Page);
274     $this->assertTrue($executable->displayHandlers->get('page_1')->default_display instanceof DefaultDisplay);
275     $this->assertTrue($executable->displayHandlers->get('page_2') instanceof Page);
276     $this->assertTrue($executable->displayHandlers->get('page_2')->default_display instanceof DefaultDisplay);
277     $this->assertTrue($executable->displayHandlers->get('display_test_1') instanceof DisplayTest);
278     $this->assertTrue($executable->displayHandlers->get('display_test_1')->default_display instanceof DefaultDisplay);
279   }
280
281   /**
282    * Tests the setting/getting of properties.
283    */
284   public function testPropertyMethods() {
285     $view = Views::getView('test_executable_displays');
286
287     // Test the setAjaxEnabled() method.
288     $this->assertFalse($view->ajaxEnabled());
289     $view->setAjaxEnabled(TRUE);
290     $this->assertTrue($view->ajaxEnabled());
291
292     $view->setDisplay();
293     // There should be no pager set initially.
294     $this->assertNull($view->usePager());
295
296     // Add a pager, initialize, and test.
297     $view->displayHandlers->get('default')->overrideOption('pager', [
298       'type' => 'full',
299       'options' => ['items_per_page' => 10],
300     ]);
301     $view->initPager();
302     $this->assertTrue($view->usePager());
303
304     // Test setting and getting the offset.
305     $rand = rand();
306     $view->setOffset($rand);
307     $this->assertEqual($view->getOffset(), $rand);
308
309     // Test the getBaseTable() method.
310     $expected = [
311       'views_test_data' => TRUE,
312       '#global' => TRUE,
313     ];
314     $this->assertIdentical($view->getBaseTables(), $expected);
315
316     // Test response methods.
317     $this->assertTrue($view->getResponse() instanceof Response, 'New response object returned.');
318     $new_response = new Response();
319     $view->setResponse($new_response);
320     $this->assertIdentical(spl_object_hash($view->getResponse()), spl_object_hash($new_response), 'New response object correctly set.');
321
322     // Test the getPath() method.
323     $path = $this->randomMachineName();
324     $view->displayHandlers->get('page_1')->overrideOption('path', $path);
325     $view->setDisplay('page_1');
326     $this->assertEqual($view->getPath(), $path);
327     // Test the override_path property override.
328     $override_path = $this->randomMachineName();
329     $view->override_path = $override_path;
330     $this->assertEqual($view->getPath(), $override_path);
331
332     // Test the title methods.
333     $title = $this->randomString();
334     $view->setTitle($title);
335     $this->assertEqual($view->getTitle(), Xss::filterAdmin($title));
336   }
337
338   /**
339    * Tests the deconstructor to be sure that necessary objects are removed.
340    */
341   public function testDestroy() {
342     $view = Views::getView('test_destroy');
343
344     $view->preview();
345     $view->destroy();
346
347     $this->assertViewDestroy($view);
348   }
349
350   /**
351    * Asserts that expected view properties have been unset by destroy().
352    *
353    * @param \Drupal\views\ViewExecutable $view
354    */
355   protected function assertViewDestroy($view) {
356     $reflection = new \ReflectionClass($view);
357     $defaults = $reflection->getDefaultProperties();
358     // The storage and user should remain.
359     unset(
360       $defaults['storage'],
361       $defaults['user'],
362       $defaults['request'],
363       $defaults['routeProvider'],
364       $defaults['viewsData']
365     );
366
367     foreach ($defaults as $property => $default) {
368       $this->assertIdentical($this->getProtectedProperty($view, $property), $default);
369     }
370   }
371
372   /**
373    * Returns a protected property from a class instance.
374    *
375    * @param object $instance
376    *   The class instance to return the property from.
377    * @param string $property
378    *   The name of the property to return.
379    *
380    * @return mixed
381    *   The instance property value.
382    */
383   protected function getProtectedProperty($instance, $property) {
384     $reflection = new \ReflectionProperty($instance, $property);
385     $reflection->setAccessible(TRUE);
386     return $reflection->getValue($instance);
387   }
388
389   /**
390    * Tests ViewExecutable::getHandlerTypes().
391    */
392   public function testGetHandlerTypes() {
393     $types = ViewExecutable::getHandlerTypes();
394     foreach (['field', 'filter', 'argument', 'sort', 'header', 'footer', 'empty'] as $type) {
395       $this->assertTrue(isset($types[$type]));
396       // @todo The key on the display should be footers, headers and empties
397       //   or something similar instead of the singular, but so long check for
398       //   this special case.
399       if (isset($types[$type]['type']) && $types[$type]['type'] == 'area') {
400         $this->assertEqual($types[$type]['plural'], $type);
401       }
402       else {
403         $this->assertEqual($types[$type]['plural'], $type . 's');
404       }
405     }
406   }
407
408   /**
409    * Tests ViewExecutable::getHandlers().
410    */
411   public function testGetHandlers() {
412     $view = Views::getView('test_executable_displays');
413     $view->setDisplay('page_1');
414
415     $view->getHandlers('field', 'page_2');
416
417     // getHandlers() shouldn't change the active display.
418     $this->assertEqual('page_1', $view->current_display, "The display shouldn't change after getHandlers()");
419   }
420
421   /**
422    * Tests the validation of display handlers.
423    */
424   public function testValidate() {
425     $view = Views::getView('test_executable_displays');
426     $view->setDisplay('page_1');
427
428     $validate = $view->validate();
429
430     // Validating a view shouldn't change the active display.
431     $this->assertEqual('page_1', $view->current_display, "The display should be constant while validating");
432
433     $count = 0;
434     foreach ($view->displayHandlers as $id => $display) {
435       $match = function ($value) use ($display) {
436         return strpos($value, $display->display['display_title']) !== FALSE;
437       };
438       $this->assertTrue(array_filter($validate[$id], $match), format_string('Error message found for @id display', ['@id' => $id]));
439       $count++;
440     }
441
442     $this->assertEqual(count($view->displayHandlers), $count, 'Error messages from all handlers merged.');
443
444     // Test that a deleted display is not included.
445     $display = &$view->storage->getDisplay('default');
446     $display['deleted'] = TRUE;
447     $validate_deleted = $view->validate();
448
449     $this->assertNotIdentical($validate, $validate_deleted, 'Master display has not been validated.');
450   }
451
452   /**
453    * Tests that nested loops of the display handlers won't break validation.
454    */
455   public function testValidateNestedLoops() {
456     $view = View::create(['id' => 'test_validate_nested_loops']);
457     $executable = $view->getExecutable();
458
459     $executable->newDisplay('display_test');
460     $executable->newDisplay('display_test');
461     $errors = $executable->validate();
462     $total_error_count = array_reduce($errors, function ($carry, $item) {
463       $carry += count($item);
464
465       return $carry;
466     });
467     // Assert that there were 9 total errors across 3 displays.
468     $this->assertIdentical(9, $total_error_count);
469     $this->assertIdentical(3, count($errors));
470   }
471
472   /**
473    * Tests serialization of the ViewExecutable object.
474    */
475   public function testSerialization() {
476     $view = Views::getView('test_executable_displays');
477     $view->setDisplay('page_1');
478     $view->setArguments(['test']);
479     $view->setCurrentPage(2);
480
481     $serialized = serialize($view);
482
483     // Test the view storage object is not present in the actual serialized
484     // string.
485     $this->assertIdentical(strpos($serialized, '"Drupal\views\Entity\View"'), FALSE, 'The Drupal\views\Entity\View class was not found in the serialized string.');
486
487     /** @var \Drupal\views\ViewExecutable $unserialized */
488     $unserialized = unserialize($serialized);
489
490     $this->assertTrue($unserialized instanceof ViewExecutable);
491     $this->assertIdentical($view->storage->id(), $unserialized->storage->id(), 'The expected storage entity was loaded on the unserialized view.');
492     $this->assertIdentical($unserialized->current_display, 'page_1', 'The expected display was set on the unserialized view.');
493     $this->assertIdentical($unserialized->args, ['test'], 'The expected argument was set on the unserialized view.');
494     $this->assertIdentical($unserialized->getCurrentPage(), 2, 'The expected current page was set on the unserialized view.');
495
496     // Get the definition of node's nid field, for example. Only get it not from
497     // the field manager directly, but from the item data definition. It should
498     // be the same base field definition object (the field and item definitions
499     // refer to each other).
500     // See https://bugs.php.net/bug.php?id=66052
501     $field_manager = $this->container->get('entity_field.manager');
502     $nid_definition_before = $field_manager->getBaseFieldDefinitions('node')['nid']
503       ->getItemDefinition()
504       ->getFieldDefinition();
505
506     // Load and execute a view.
507     $view_entity = View::load('content');
508     $view_executable = $view_entity->getExecutable();
509     $view_executable->execute('page_1');
510
511     // Reset the static cache. Don't use clearCachedFieldDefinitions() since
512     // that clears the persistent cache and we need to get the serialized cache
513     // data.
514     $field_manager->useCaches(FALSE);
515     $field_manager->useCaches(TRUE);
516
517     // Serialize the ViewExecutable as part of other data.
518     unserialize(serialize(['SOMETHING UNEXPECTED', $view_executable]));
519
520     // Make sure the serialisation of the ViewExecutable didn't influence the
521     // field definitions.
522     $nid_definition_after = $field_manager->getBaseFieldDefinitions('node')['nid']
523       ->getItemDefinition()
524       ->getFieldDefinition();
525     $this->assertEquals($nid_definition_before->getPropertyDefinitions(), $nid_definition_after->getPropertyDefinitions());
526   }
527
528   /**
529    * Tests if argument overrides by validators are propagated to tokens.
530    */
531   public function testArgumentValidatorValueOverride() {
532     $view = Views::getView('test_argument_dependency');
533     $view->setDisplay('page_1');
534     $view->setArguments(['1', 'this value should be replaced']);
535     $view->execute();
536     $expected = [
537       '{{ arguments.uid }}' => '1',
538       '{{ raw_arguments.uid }}' => '1',
539     ];
540     $this->assertEquals($expected, $view->build_info['substitutions']);
541   }
542
543 }