1333c6225b9828357988ecb5a22fe97d36354428
[yaffs-website] / ModuleTest.php
1 <?php
2
3 namespace Drupal\Tests\views\Kernel;
4
5 /**
6  * Tests basic functions from the Views module.
7  *
8  * @group views
9  */
10 use Drupal\views\Plugin\views\filter\Standard;
11 use Drupal\views\Views;
12 use Drupal\Component\Render\FormattableMarkup;
13
14 class ModuleTest extends ViewsKernelTestBase {
15
16   /**
17    * Views used by this test.
18    *
19    * @var array
20    */
21   public static $testViews = ['test_view_status', 'test_view', 'test_argument'];
22
23   /**
24    * Modules to enable.
25    *
26    * @var array
27    */
28   public static $modules = ['field', 'user', 'block'];
29
30   /**
31    * Stores the last triggered error.
32    *
33    * @var string
34    *
35    * @see \Drupal\views\Tests\ModuleTest::errorHandler()
36    */
37   protected $lastErrorMessage;
38
39   /**
40    * Tests the  ViewsHandlerManager::getHandler() method.
41    *
42    * @see \Drupal\views\Plugin\ViewsHandlerManager::getHandler()
43    */
44   public function testViewsGetHandler() {
45     $types = ['field', 'area', 'filter'];
46     foreach ($types as $type) {
47       $item = [
48         'table' => $this->randomMachineName(),
49         'field' => $this->randomMachineName(),
50       ];
51       $handler = $this->container->get('plugin.manager.views.' . $type)->getHandler($item);
52       $this->assertEqual('Drupal\views\Plugin\views\\' . $type . '\Broken', get_class($handler), new FormattableMarkup('Make sure that a broken handler of type: @type is created.', ['@type' => $type]));
53     }
54
55     $views_data = $this->viewsData();
56     $test_tables = ['views_test_data' => ['id', 'name']];
57     foreach ($test_tables as $table => $fields) {
58       foreach ($fields as $field) {
59         $data = $views_data[$table][$field];
60         $item = [
61           'table' => $table,
62           'field' => $field,
63         ];
64         foreach ($data as $id => $field_data) {
65           if (!in_array($id, ['title', 'help'])) {
66             $handler = $this->container->get('plugin.manager.views.' . $id)->getHandler($item);
67             $this->assertInstanceHandler($handler, $table, $field, $id);
68           }
69         }
70       }
71     }
72
73     // Test the override handler feature.
74     $item = [
75       'table' => 'views_test_data',
76       'field' => 'job',
77     ];
78     $handler = $this->container->get('plugin.manager.views.filter')->getHandler($item, 'standard');
79     $this->assertTrue($handler instanceof Standard);
80
81     // @todo Reinstate these tests when the debug() in views_get_handler() is
82     //   restored.
83     return;
84
85     // Test non-existent tables/fields.
86     set_error_handler([$this, 'customErrorHandler']);
87     $item = [
88       'table' => 'views_test_data',
89       'field' => 'field_invalid',
90     ];
91     $this->container->get('plugin.manager.views.field')->getHandler($item);
92     $this->assertTrue(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", ['@table' => 'views_test_data', '@field' => 'field_invalid', '@type' => 'field'])) !== FALSE, 'An invalid field name throws a debug message.');
93     unset($this->lastErrorMessage);
94
95     $item = [
96       'table' => 'table_invalid',
97       'field' => 'id',
98     ];
99     $this->container->get('plugin.manager.views.filter')->getHandler($item);
100     $this->assertEqual(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", ['@table' => 'table_invalid', '@field' => 'id', '@type' => 'filter'])) !== FALSE, 'An invalid table name throws a debug message.');
101     unset($this->lastErrorMessage);
102
103     $item = [
104       'table' => 'table_invalid',
105       'field' => 'id',
106     ];
107     $this->container->get('plugin.manager.views.filter')->getHandler($item);
108     $this->assertEqual(strpos($this->lastErrorMessage, format_string("Missing handler: @table @field @type", ['@table' => 'table_invalid', '@field' => 'id', '@type' => 'filter'])) !== FALSE, 'An invalid table name throws a debug message.');
109     unset($this->lastErrorMessage);
110
111     restore_error_handler();
112   }
113
114   /**
115    * Defines an error handler which is used in the test.
116    *
117    * Because this is registered in set_error_handler(), it has to be public.
118    *
119    * @param int $error_level
120    *   The level of the error raised.
121    * @param string $message
122    *   The error message.
123    * @param string $filename
124    *   The filename that the error was raised in.
125    * @param int $line
126    *   The line number the error was raised at.
127    * @param array $context
128    *   An array that points to the active symbol table at the point the error
129    *   occurred.
130    *
131    * @see set_error_handler()
132    */
133   public function customErrorHandler($error_level, $message, $filename, $line, $context) {
134     $this->lastErrorMessage = $message;
135   }
136
137   /**
138    * Tests the load wrapper/helper functions.
139    */
140   public function testLoadFunctions() {
141     $this->enableModules(['text', 'node']);
142     $this->installConfig(['node']);
143     $storage = $this->container->get('entity.manager')->getStorage('view');
144
145     // Test views_view_is_enabled/disabled.
146     $archive = $storage->load('archive');
147     $this->assertTrue(views_view_is_disabled($archive), 'views_view_is_disabled works as expected.');
148     // Enable the view and check this.
149     $archive->enable();
150     $this->assertTrue(views_view_is_enabled($archive), ' views_view_is_enabled works as expected.');
151
152     // We can store this now, as we have enabled/disabled above.
153     $all_views = $storage->loadMultiple();
154
155     // Test Views::getAllViews().
156     ksort($all_views);
157     $this->assertEquals(array_keys($all_views), array_keys(Views::getAllViews()), 'Views::getAllViews works as expected.');
158
159     // Test Views::getEnabledViews().
160     $expected_enabled = array_filter($all_views, function ($view) {
161       return views_view_is_enabled($view);
162     });
163     $this->assertEquals(array_keys($expected_enabled), array_keys(Views::getEnabledViews()), 'Expected enabled views returned.');
164
165     // Test Views::getDisabledViews().
166     $expected_disabled = array_filter($all_views, function ($view) {
167       return views_view_is_disabled($view);
168     });
169     $this->assertEquals(array_keys($expected_disabled), array_keys(Views::getDisabledViews()), 'Expected disabled views returned.');
170
171     // Test Views::getViewsAsOptions().
172     // Test the $views_only parameter.
173     $this->assertIdentical(array_keys($all_views), array_keys(Views::getViewsAsOptions(TRUE)), 'Expected option keys for all views were returned.');
174     $expected_options = [];
175     foreach ($all_views as $id => $view) {
176       $expected_options[$id] = $view->label();
177     }
178     $this->assertIdentical($expected_options, $this->castSafeStrings(Views::getViewsAsOptions(TRUE)), 'Expected options array was returned.');
179
180     // Test the default.
181     $this->assertIdentical($this->formatViewOptions($all_views), $this->castSafeStrings(Views::getViewsAsOptions()), 'Expected options array for all views was returned.');
182     // Test enabled views.
183     $this->assertIdentical($this->formatViewOptions($expected_enabled), $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'enabled')), 'Expected enabled options array was returned.');
184     // Test disabled views.
185     $this->assertIdentical($this->formatViewOptions($expected_disabled), $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'disabled')), 'Expected disabled options array was returned.');
186
187     // Test the sort parameter.
188     $all_views_sorted = $all_views;
189     ksort($all_views_sorted);
190     $this->assertIdentical(array_keys($all_views_sorted), array_keys(Views::getViewsAsOptions(TRUE, 'all', NULL, FALSE, TRUE)), 'All view id keys returned in expected sort order');
191
192     // Test $exclude_view parameter.
193     $this->assertFalse(array_key_exists('archive', Views::getViewsAsOptions(TRUE, 'all', 'archive')), 'View excluded from options based on name');
194     $this->assertFalse(array_key_exists('archive:default', Views::getViewsAsOptions(FALSE, 'all', 'archive:default')), 'View display excluded from options based on name');
195     $this->assertFalse(array_key_exists('archive', Views::getViewsAsOptions(TRUE, 'all', $archive->getExecutable())), 'View excluded from options based on object');
196
197     // Test the $opt_group parameter.
198     $expected_opt_groups = [];
199     foreach ($all_views as $view) {
200       foreach ($view->get('display') as $display) {
201         $expected_opt_groups[$view->id()][$view->id() . ':' . $display['id']] = (string) t('@view : @display', ['@view' => $view->id(), '@display' => $display['id']]);
202       }
203     }
204     $this->assertIdentical($expected_opt_groups, $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'all', NULL, TRUE)), 'Expected option array for an option group returned.');
205   }
206
207   /**
208    * Tests view enable and disable procedural wrapper functions.
209    */
210   public function testStatusFunctions() {
211     $view = Views::getView('test_view_status')->storage;
212
213     $this->assertFalse($view->status(), 'The view status is disabled.');
214
215     views_enable_view($view);
216     $this->assertTrue($view->status(), 'A view has been enabled.');
217     $this->assertEqual($view->status(), views_view_is_enabled($view), 'views_view_is_enabled is correct.');
218
219     views_disable_view($view);
220     $this->assertFalse($view->status(), 'A view has been disabled.');
221     $this->assertEqual(!$view->status(), views_view_is_disabled($view), 'views_view_is_disabled is correct.');
222   }
223
224   /**
225    * Tests the \Drupal\views\Views::fetchPluginNames() method.
226    */
227   public function testViewsFetchPluginNames() {
228     // All style plugins should be returned, as we have not specified a type.
229     $plugins = Views::fetchPluginNames('style');
230     $definitions = $this->container->get('plugin.manager.views.style')->getDefinitions();
231     $expected = [];
232     foreach ($definitions as $id => $definition) {
233       $expected[$id] = $definition['title'];
234     }
235     asort($expected);
236     $this->assertIdentical(array_keys($plugins), array_keys($expected));
237
238     // Test using the 'test' style plugin type only returns the test_style and
239     // mapping_test plugins.
240     $plugins = Views::fetchPluginNames('style', 'test');
241     $this->assertIdentical(array_keys($plugins), ['mapping_test', 'test_style', 'test_template_style']);
242
243     // Test a non existent style plugin type returns no plugins.
244     $plugins = Views::fetchPluginNames('style', $this->randomString());
245     $this->assertIdentical($plugins, []);
246   }
247
248   /**
249    * Tests the \Drupal\views\Views::pluginList() method.
250    */
251   public function testViewsPluginList() {
252     $plugin_list = Views::pluginList();
253     // Only plugins used by 'test_view' should be in the plugin list.
254     foreach (['display:default', 'pager:none'] as $key) {
255       list($plugin_type, $plugin_id) = explode(':', $key);
256       $plugin_def = $this->container->get("plugin.manager.views.$plugin_type")->getDefinition($plugin_id);
257
258       $this->assertTrue(isset($plugin_list[$key]), new FormattableMarkup('The expected @key plugin list key was found.', ['@key' => $key]));
259       $plugin_details = $plugin_list[$key];
260
261       $this->assertEqual($plugin_details['type'], $plugin_type, 'The expected plugin type was found.');
262       $this->assertEqual($plugin_details['title'], $plugin_def['title'], 'The expected plugin title was found.');
263       $this->assertEqual($plugin_details['provider'], $plugin_def['provider'], 'The expected plugin provider was found.');
264       $this->assertTrue(in_array('test_view', $plugin_details['views']), 'The test_view View was found in the list of views using this plugin.');
265     }
266   }
267
268   /**
269    * Tests views.module: views_embed_view().
270    */
271   public function testViewsEmbedView() {
272     /** @var \Drupal\Core\Render\RendererInterface $renderer */
273     $renderer = \Drupal::service('renderer');
274
275     $result = views_embed_view('test_argument');
276     $renderer->renderPlain($result);
277     $this->assertEqual(count($result['view_build']['#view']->result), 5);
278
279     $result = views_embed_view('test_argument', 'default', 1);
280     $renderer->renderPlain($result);
281     $this->assertEqual(count($result['view_build']['#view']->result), 1);
282
283     $result = views_embed_view('test_argument', 'default', '1,2');
284     $renderer->renderPlain($result);
285     $this->assertEqual(count($result['view_build']['#view']->result), 2);
286
287     $result = views_embed_view('test_argument', 'default', '1,2', 'John');
288     $renderer->renderPlain($result);
289     $this->assertEqual(count($result['view_build']['#view']->result), 1);
290
291     $result = views_embed_view('test_argument', 'default', '1,2', 'John,George');
292     $renderer->renderPlain($result);
293     $this->assertEqual(count($result['view_build']['#view']->result), 2);
294   }
295
296   /**
297    * Tests the \Drupal\views\ViewsExecutable::preview() method.
298    */
299   public function testViewsPreview() {
300     $view = Views::getView('test_argument');
301     $result = $view->preview('default');
302     $this->assertEqual(count($result['#view']->result), 5);
303
304     $view = Views::getView('test_argument');
305     $result = $view->preview('default', ['0' => 1]);
306     $this->assertEqual(count($result['#view']->result), 1);
307
308     $view = Views::getView('test_argument');
309     $result = $view->preview('default', ['3' => 1]);
310     $this->assertEqual(count($result['#view']->result), 1);
311
312     $view = Views::getView('test_argument');
313     $result = $view->preview('default', ['0' => '1,2']);
314     $this->assertEqual(count($result['#view']->result), 2);
315
316     $view = Views::getView('test_argument');
317     $result = $view->preview('default', ['3' => '1,2']);
318     $this->assertEqual(count($result['#view']->result), 2);
319
320     $view = Views::getView('test_argument');
321     $result = $view->preview('default', ['0' => '1,2', '1' => 'John']);
322     $this->assertEqual(count($result['#view']->result), 1);
323
324     $view = Views::getView('test_argument');
325     $result = $view->preview('default', ['3' => '1,2', '4' => 'John']);
326     $this->assertEqual(count($result['#view']->result), 1);
327
328     $view = Views::getView('test_argument');
329     $result = $view->preview('default', ['0' => '1,2', '1' => 'John,George']);
330     $this->assertEqual(count($result['#view']->result), 2);
331
332     $view = Views::getView('test_argument');
333     $result = $view->preview('default', ['3' => '1,2', '4' => 'John,George']);
334     $this->assertEqual(count($result['#view']->result), 2);
335   }
336
337   /**
338    * Helper to return an expected views option array.
339    *
340    * @param array $views
341    *   An array of Drupal\views\Entity\View objects for which to
342    *   create an options array.
343    *
344    * @return array
345    *   A formatted options array that matches the expected output.
346    */
347   protected function formatViewOptions(array $views = []) {
348     $expected_options = [];
349     foreach ($views as $view) {
350       foreach ($view->get('display') as $display) {
351         $expected_options[$view->id() . ':' . $display['id']] = (string) t('View: @view - Display: @display',
352           ['@view' => $view->id(), '@display' => $display['id']]);
353       }
354     }
355
356     return $expected_options;
357   }
358
359   /**
360    * Ensure that a certain handler is a instance of a certain table/field.
361    */
362   public function assertInstanceHandler($handler, $table, $field, $id) {
363     $table_data = $this->container->get('views.views_data')->get($table);
364     $field_data = $table_data[$field][$id];
365
366     $this->assertEqual($field_data['id'], $handler->getPluginId());
367   }
368
369 }