ModuleTest.php 13.5 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2
<?php

3
namespace Drupal\Tests\views\Kernel;
4

5 6 7 8 9 10 11 12
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Form\FormState;
use Drupal\views\Plugin\views\area\Broken as BrokenArea;
use Drupal\views\Plugin\views\field\Broken as BrokenField;
use Drupal\views\Plugin\views\filter\Broken as BrokenFilter;
use Drupal\views\Plugin\views\filter\Standard;
use Drupal\views\Views;

merlinofchaos's avatar
merlinofchaos committed
13 14
/**
 * Tests basic functions from the Views module.
15 16
 *
 * @group views
merlinofchaos's avatar
merlinofchaos committed
17
 */
18
class ModuleTest extends ViewsKernelTestBase {
19

20 21 22 23 24
  /**
   * Views used by this test.
   *
   * @var array
   */
25
  public static $testViews = ['test_view_status', 'test_view', 'test_argument'];
26

27 28 29 30 31
  /**
   * Modules to enable.
   *
   * @var array
   */
32
  protected static $modules = ['field', 'user', 'block'];
33

34
  /**
35
   * Stores the last triggered error.
36 37 38 39 40 41 42
   *
   * @var string
   *
   * @see \Drupal\views\Tests\ModuleTest::errorHandler()
   */
  protected $lastErrorMessage;

merlinofchaos's avatar
merlinofchaos committed
43
  /**
44
   * Tests the  ViewsHandlerManager::getHandler() method.
45
   *
46
   * @see \Drupal\views\Plugin\ViewsHandlerManager::getHandler()
merlinofchaos's avatar
merlinofchaos committed
47
   */
48
  public function testViewsGetHandler() {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    $types = [
      'field' => BrokenField::class,
      'area' => BrokenArea::class,
      'filter' => BrokenFilter::class,
    ];
    // Test non-existent tables/fields.
    $items = [
      [
        'table' => 'table_invalid',
        'field' => 'id',
      ],
      [
        'table' => 'views_test_data',
        'field' => 'field_invalid',
      ],
    ];
    $form_state = new FormState();
    $description_top = '<p>' . t('The handler for this item is broken or missing. The following details are available:') . '</p>';
    $description_bottom = '<p>' . t('Enabling the appropriate module may solve this issue. Otherwise, check to see if there is a module update available.') . '</p>';
    foreach ($types as $type => $class) {
      foreach ($items as $item) {
        $handler = $this->container->get('plugin.manager.views.' . $type)
          ->getHandler($item);
        $this->assertTrue($handler instanceof $class);
        // Make sure details available at edit form.
        $form = [];
        $handler->buildOptionsForm($form, $form_state);
        $this->assertEquals($description_top, $form['description']['description_top']['#markup']);
        $this->assertEquals($description_bottom, $form['description']['description_bottom']['#markup']);
        $details = [];
        foreach ($item as $key => $value) {
          $details[] = new FormattableMarkup('@key: @value', ['@key' => $key, '@value' => $value]);
        }
        $this->assertEquals($details, $form['description']['detail_list']['#items']);
      }
merlinofchaos's avatar
merlinofchaos committed
84 85 86
    }

    $views_data = $this->viewsData();
87
    $test_tables = ['views_test_data' => ['id', 'name']];
merlinofchaos's avatar
merlinofchaos committed
88 89 90
    foreach ($test_tables as $table => $fields) {
      foreach ($fields as $field) {
        $data = $views_data[$table][$field];
91
        $item = [
92 93
          'table' => $table,
          'field' => $field,
94
        ];
merlinofchaos's avatar
merlinofchaos committed
95
        foreach ($data as $id => $field_data) {
96
          if (!in_array($id, ['title', 'help'])) {
97
            $handler = $this->container->get('plugin.manager.views.' . $id)->getHandler($item);
merlinofchaos's avatar
merlinofchaos committed
98 99 100 101 102 103
            $this->assertInstanceHandler($handler, $table, $field, $id);
          }
        }
      }
    }

104
    // Test the override handler feature.
105
    $item = [
106 107
      'table' => 'views_test_data',
      'field' => 'job',
108
    ];
109
    $handler = $this->container->get('plugin.manager.views.filter')->getHandler($item, 'standard');
110
    $this->assertInstanceOf(Standard::class, $handler);
merlinofchaos's avatar
merlinofchaos committed
111 112
  }

113 114 115 116
  /**
   * Tests the load wrapper/helper functions.
   */
  public function testLoadFunctions() {
117
    $this->enableModules(['text', 'node']);
118
    $this->installEntitySchema('node');
119
    $this->installConfig(['node']);
120
    $storage = $this->container->get('entity_type.manager')->getStorage('view');
121 122

    // Test views_view_is_enabled/disabled.
123
    $archive = $storage->load('archive');
124 125 126 127 128 129
    $this->assertTrue(views_view_is_disabled($archive), 'views_view_is_disabled works as expected.');
    // Enable the view and check this.
    $archive->enable();
    $this->assertTrue(views_view_is_enabled($archive), ' views_view_is_enabled works as expected.');

    // We can store this now, as we have enabled/disabled above.
130
    $all_views = $storage->loadMultiple();
131

132
    // Test Views::getAllViews().
133 134
    ksort($all_views);
    $this->assertEquals(array_keys($all_views), array_keys(Views::getAllViews()), 'Views::getAllViews works as expected.');
135

136
    // Test Views::getEnabledViews().
137
    $expected_enabled = array_filter($all_views, function ($view) {
138 139
      return views_view_is_enabled($view);
    });
140
    $this->assertEquals(array_keys($expected_enabled), array_keys(Views::getEnabledViews()), 'Expected enabled views returned.');
141

142
    // Test Views::getDisabledViews().
143
    $expected_disabled = array_filter($all_views, function ($view) {
144 145
      return views_view_is_disabled($view);
    });
146
    $this->assertEquals(array_keys($expected_disabled), array_keys(Views::getDisabledViews()), 'Expected disabled views returned.');
147

148
    // Test Views::getViewsAsOptions().
149
    // Test the $views_only parameter.
150
    $this->assertIdentical(array_keys($all_views), array_keys(Views::getViewsAsOptions(TRUE)), 'Expected option keys for all views were returned.');
151
    $expected_options = [];
152
    foreach ($all_views as $id => $view) {
153
      $expected_options[$id] = $view->label();
154
    }
155
    $this->assertIdentical($expected_options, $this->castSafeStrings(Views::getViewsAsOptions(TRUE)), 'Expected options array was returned.');
156 157

    // Test the default.
158
    $this->assertIdentical($this->formatViewOptions($all_views), $this->castSafeStrings(Views::getViewsAsOptions()), 'Expected options array for all views was returned.');
159
    // Test enabled views.
160
    $this->assertIdentical($this->formatViewOptions($expected_enabled), $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'enabled')), 'Expected enabled options array was returned.');
161
    // Test disabled views.
162
    $this->assertIdentical($this->formatViewOptions($expected_disabled), $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'disabled')), 'Expected disabled options array was returned.');
163 164 165 166

    // Test the sort parameter.
    $all_views_sorted = $all_views;
    ksort($all_views_sorted);
167
    $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');
168 169

    // Test $exclude_view parameter.
170 171 172
    $this->assertArrayNotHasKey('archive', Views::getViewsAsOptions(TRUE, 'all', 'archive'));
    $this->assertArrayNotHasKey('archive:default', Views::getViewsAsOptions(FALSE, 'all', 'archive:default'));
    $this->assertArrayNotHasKey('archive', Views::getViewsAsOptions(TRUE, 'all', $archive->getExecutable()));
173 174

    // Test the $opt_group parameter.
175
    $expected_opt_groups = [];
176 177
    foreach ($all_views as $view) {
      foreach ($view->get('display') as $display) {
178
        $expected_opt_groups[$view->id()][$view->id() . ':' . $display['id']] = (string) t('@view : @display', ['@view' => $view->id(), '@display' => $display['id']]);
179 180
      }
    }
181
    $this->assertIdentical($expected_opt_groups, $this->castSafeStrings(Views::getViewsAsOptions(FALSE, 'all', NULL, TRUE)), 'Expected option array for an option group returned.');
182 183 184 185 186
  }

  /**
   * Tests view enable and disable procedural wrapper functions.
   */
187
  public function testStatusFunctions() {
188
    $view = Views::getView('test_view_status')->storage;
189

190
    $this->assertFalse($view->status(), 'The view status is disabled.');
191 192

    views_enable_view($view);
193 194
    $this->assertTrue($view->status(), 'A view has been enabled.');
    $this->assertEqual($view->status(), views_view_is_enabled($view), 'views_view_is_enabled is correct.');
195 196

    views_disable_view($view);
197 198
    $this->assertFalse($view->status(), 'A view has been disabled.');
    $this->assertEqual(!$view->status(), views_view_is_disabled($view), 'views_view_is_disabled is correct.');
199 200
  }

201
  /**
202
   * Tests the \Drupal\views\Views::fetchPluginNames() method.
203 204 205
   */
  public function testViewsFetchPluginNames() {
    // All style plugins should be returned, as we have not specified a type.
206
    $plugins = Views::fetchPluginNames('style');
207
    $definitions = $this->container->get('plugin.manager.views.style')->getDefinitions();
208
    $expected = [];
209
    foreach ($definitions as $id => $definition) {
210 211 212 213 214 215 216
      $expected[$id] = $definition['title'];
    }
    asort($expected);
    $this->assertIdentical(array_keys($plugins), array_keys($expected));

    // Test using the 'test' style plugin type only returns the test_style and
    // mapping_test plugins.
217
    $plugins = Views::fetchPluginNames('style', 'test');
218
    $this->assertIdentical(array_keys($plugins), ['mapping_test', 'test_style', 'test_template_style']);
219 220

    // Test a non existent style plugin type returns no plugins.
221
    $plugins = Views::fetchPluginNames('style', $this->randomString());
222
    $this->assertIdentical($plugins, []);
223 224
  }

225
  /**
226
   * Tests the \Drupal\views\Views::pluginList() method.
227 228
   */
  public function testViewsPluginList() {
229
    $plugin_list = Views::pluginList();
230
    // Only plugins used by 'test_view' should be in the plugin list.
231
    foreach (['display:default', 'pager:none'] as $key) {
232 233 234
      list($plugin_type, $plugin_id) = explode(':', $key);
      $plugin_def = $this->container->get("plugin.manager.views.$plugin_type")->getDefinition($plugin_id);

235
      $this->assertTrue(isset($plugin_list[$key]), new FormattableMarkup('The expected @key plugin list key was found.', ['@key' => $key]));
236 237 238 239 240
      $plugin_details = $plugin_list[$key];

      $this->assertEqual($plugin_details['type'], $plugin_type, 'The expected plugin type was found.');
      $this->assertEqual($plugin_details['title'], $plugin_def['title'], 'The expected plugin title was found.');
      $this->assertEqual($plugin_details['provider'], $plugin_def['provider'], 'The expected plugin provider was found.');
241
      $this->assertContains('test_view', $plugin_details['views'], 'The test_view View was found in the list of views using this plugin.');
242 243 244
    }
  }

245 246 247 248
  /**
   * Tests views.module: views_embed_view().
   */
  public function testViewsEmbedView() {
249 250 251
    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = \Drupal::service('renderer');

252
    $result = views_embed_view('test_argument');
253
    $renderer->renderPlain($result);
254
    $this->assertCount(5, $result['view_build']['#view']->result);
255 256

    $result = views_embed_view('test_argument', 'default', 1);
257
    $renderer->renderPlain($result);
258
    $this->assertCount(1, $result['view_build']['#view']->result);
259 260

    $result = views_embed_view('test_argument', 'default', '1,2');
261
    $renderer->renderPlain($result);
262
    $this->assertCount(2, $result['view_build']['#view']->result);
263 264

    $result = views_embed_view('test_argument', 'default', '1,2', 'John');
265
    $renderer->renderPlain($result);
266
    $this->assertCount(1, $result['view_build']['#view']->result);
267 268

    $result = views_embed_view('test_argument', 'default', '1,2', 'John,George');
269
    $renderer->renderPlain($result);
270
    $this->assertCount(2, $result['view_build']['#view']->result);
271 272 273 274 275 276 277 278
  }

  /**
   * Tests the \Drupal\views\ViewsExecutable::preview() method.
   */
  public function testViewsPreview() {
    $view = Views::getView('test_argument');
    $result = $view->preview('default');
279
    $this->assertCount(5, $result['#view']->result);
280 281

    $view = Views::getView('test_argument');
282
    $result = $view->preview('default', ['0' => 1]);
283
    $this->assertCount(1, $result['#view']->result);
284 285

    $view = Views::getView('test_argument');
286
    $result = $view->preview('default', ['3' => 1]);
287
    $this->assertCount(1, $result['#view']->result);
288 289

    $view = Views::getView('test_argument');
290
    $result = $view->preview('default', ['0' => '1,2']);
291
    $this->assertCount(2, $result['#view']->result);
292 293

    $view = Views::getView('test_argument');
294
    $result = $view->preview('default', ['3' => '1,2']);
295
    $this->assertCount(2, $result['#view']->result);
296 297

    $view = Views::getView('test_argument');
298
    $result = $view->preview('default', ['0' => '1,2', '1' => 'John']);
299
    $this->assertCount(1, $result['#view']->result);
300 301

    $view = Views::getView('test_argument');
302
    $result = $view->preview('default', ['3' => '1,2', '4' => 'John']);
303
    $this->assertCount(1, $result['#view']->result);
304 305

    $view = Views::getView('test_argument');
306
    $result = $view->preview('default', ['0' => '1,2', '1' => 'John,George']);
307
    $this->assertCount(2, $result['#view']->result);
308 309

    $view = Views::getView('test_argument');
310
    $result = $view->preview('default', ['3' => '1,2', '4' => 'John,George']);
311
    $this->assertCount(2, $result['#view']->result);
312 313
  }

314 315 316 317
  /**
   * Helper to return an expected views option array.
   *
   * @param array $views
318
   *   An array of Drupal\views\Entity\View objects for which to
319
   *   create an options array.
320 321 322 323
   *
   * @return array
   *   A formatted options array that matches the expected output.
   */
324 325
  protected function formatViewOptions(array $views = []) {
    $expected_options = [];
326 327
    foreach ($views as $view) {
      foreach ($view->get('display') as $display) {
328
        $expected_options[$view->id() . ':' . $display['id']] = (string) t('View: @view - Display: @display',
329
          ['@view' => $view->id(), '@display' => $display['id']]);
330 331 332 333 334 335
      }
    }

    return $expected_options;
  }

merlinofchaos's avatar
merlinofchaos committed
336 337 338
  /**
   * Ensure that a certain handler is a instance of a certain table/field.
   */
339
  public function assertInstanceHandler($handler, $table, $field, $id) {
340
    $table_data = $this->container->get('views.views_data')->get($table);
merlinofchaos's avatar
merlinofchaos committed
341 342
    $field_data = $table_data[$field][$id];

aspilicious's avatar
aspilicious committed
343
    $this->assertEqual($field_data['id'], $handler->getPluginId());
merlinofchaos's avatar
merlinofchaos committed
344
  }
345

merlinofchaos's avatar
merlinofchaos committed
346
}