/** * Tests the filter UI. */ public function testFilterUI() { $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid'); $result = $this->xpath('//select[@id="edit-options-value"]/option'); // Ensure that the expected hierarchy is available in the UI. $counter = 0; for ($i = 0; $i < 3; $i++) { for ($j = 0; $j <= $i; $j++) { $option = $result[$counter++]; $prefix = $this->terms[$i][$j]->parent->target_id ? '-' : ''; $attributes = $option->attributes(); $tid = (string) $attributes->value; $this->assertEqual($prefix . $this->terms[$i][$j]->getName(), (string) $option); $this->assertEqual($this->terms[$i][$j]->id(), $tid); } } // Ensure the autocomplete input element appears when using the 'textfield' // type. $view = View::load('test_filter_taxonomy_index_tid'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['tid']['type'] = 'textfield'; $view->save(); $this->drupalGet('admin/structure/views/nojs/handler/test_filter_taxonomy_index_tid/default/filter/tid'); $this->assertFieldByXPath('//input[@id="edit-options-value"]'); // Tests \Drupal\taxonomy\Plugin\views\filter\TaxonomyIndexTid::calculateDependencies(). $expected = ['config' => ['taxonomy.vocabulary.tags'], 'content' => ['taxonomy_term:tags:' . Term::load(2)->uuid()], 'module' => ['node', 'taxonomy', 'user']]; $this->assertIdentical($expected, $view->calculateDependencies()->getDependencies()); }
/** * Test the username formatter. */ public function testUsername() { $view_id = $this->randomMachineName(); $view = View::create(['id' => $view_id, 'base_table' => 'comment_field_data', 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => ['name' => ['table' => 'comment_field_data', 'field' => 'name', 'id' => 'name', 'plugin_id' => 'field', 'type' => 'comment_username'], 'subject' => ['table' => 'comment_field_data', 'field' => 'subject', 'id' => 'subject', 'plugin_id' => 'field', 'type' => 'string', 'settings' => ['link_to_entity' => TRUE]]]]]]]); $view->save(); /* @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */ $account_switcher = \Drupal::service('account_switcher'); /* @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $account_switcher->switchTo($this->adminUser); $executable = Views::getView($view_id); $build = $executable->preview(); $this->setRawContent($renderer->renderRoot($build)); $this->verbose($this->getRawContent()); $this->assertLink('My comment title'); $this->assertLink('Anonymous comment title'); $this->assertLink($this->adminUser->label()); $this->assertLink('barry (not verified)'); $account_switcher->switchTo(new AnonymousUserSession()); $executable = Views::getView($view_id); $executable->storage->invalidateCaches(); $build = $executable->preview(); $this->setRawContent($renderer->renderRoot($build)); // No access to user-profiles, so shouldn't be able to see links. $this->assertNoLink($this->adminUser->label()); // Note: External users aren't pointing to drupal user profiles. $this->assertLink('barry (not verified)'); $this->verbose($this->getRawContent()); $this->assertLink('My comment title'); $this->assertLink('Anonymous comment title'); }
/** * Checks views field access for a given entity type and field name. * * To use this method, set up an entity of type $entity_type_id, with field * $field_name. Create an entity instance that contains content $field_content * in that field. * * This method will check that a user with permission can see the content in a * view, and a user without access permission on that field cannot. * * @param string $entity_type_id * The entity type ID. * @param string $field_name * The field name. * @param string $field_content * The expected field content. */ protected function assertFieldAccess($entity_type_id, $field_name, $field_content) { \Drupal::state()->set('views_field_access_test-field', $field_name); $entity_type = \Drupal::entityManager()->getDefinition($entity_type_id); $view_id = $this->randomMachineName(); $data_table = $entity_type->getDataTable(); // Use the data table as long as the field is not 'uuid'. This is the only // column that can only be obtained from the base table. $base_table = $data_table && $field_name !== 'uuid' ? $data_table : $entity_type->getBaseTable(); $entity = View::create(['id' => $view_id, 'base_table' => $base_table, 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => [$field_name => ['table' => $base_table, 'field' => $field_name, 'id' => $field_name, 'plugin_id' => 'field']]]]]]); $entity->save(); /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */ $account_switcher = \Drupal::service('account_switcher'); /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $account_switcher->switchTo($this->userWithAccess); $executable = Views::getView($view_id); $build = $executable->preview(); $this->setRawContent($renderer->renderRoot($build)); $this->assertText($field_content); $this->assertTrue(isset($executable->field[$field_name])); $account_switcher->switchTo($this->userWithoutAccess); $executable = Views::getView($view_id); $build = $executable->preview(); $this->setRawContent($renderer->renderRoot($build)); $this->assertNoText($field_content); $this->assertFalse(isset($executable->field[$field_name])); \Drupal::state()->delete('views_field_access_test-field'); }
public function testUI() { // Set up a block and a entity_test entity. $block = Block::create(['id' => 'test_id', 'plugin' => 'system_main_block']); $block->save(); $entity_test = EntityTest::create(['bundle' => 'entity_test']); $entity_test->save(); $default = $this->randomView([]); $id = $default['id']; $view = View::load($id); $this->drupalGet($view->urlInfo('edit-form')); // Add a global NULL argument to the view for testing argument placeholders. $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/argument", ['name[views.null]' => 1], 'Add and configure contextual filters'); $this->drupalPostForm(NULL, [], 'Apply'); // Configure both the entity_test area header and the block header to // reference the given entities. $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/header", ['name[views.entity_block]' => 1], 'Add and configure header'); $this->drupalPostForm(NULL, ['options[target]' => $block->id()], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/add-handler/{$id}/page_1/header", ['name[views.entity_entity_test]' => 1], 'Add and configure header'); $this->drupalPostForm(NULL, ['options[target]' => $entity_test->id()], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm the correct target identifiers were saved for both entities. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual($block->id(), $header['entity_block']['target']); $this->assertEqual($entity_test->uuid(), $header['entity_entity_test']['target']); // Confirm that the correct serial ID (for the entity_test) and config ID // (for the block) are displayed in the form. $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block"); $this->assertFieldByName('options[target]', $block->id()); $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test"); $this->assertFieldByName('options[target]', $entity_test->id()); // Replace the header target entities with argument placeholders. $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block", ['options[target]' => '{{ raw_arguments.null }}'], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test", ['options[target]' => '{{ raw_arguments.null }}'], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm that the argument placeholders are saved. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual('{{ raw_arguments.null }}', $header['entity_block']['target']); $this->assertEqual('{{ raw_arguments.null }}', $header['entity_entity_test']['target']); // Confirm that the argument placeholders are still displayed in the form. $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block"); $this->assertFieldByName('options[target]', '{{ raw_arguments.null }}'); $this->drupalGet("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test"); $this->assertFieldByName('options[target]', '{{ raw_arguments.null }}'); // Change the targets for both headers back to the entities. $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_block", ['options[target]' => $block->id()], 'Apply'); $this->drupalPostForm("admin/structure/views/nojs/handler/{$id}/page_1/header/entity_entity_test", ['options[target]' => $entity_test->id()], 'Apply'); $this->drupalPostForm(NULL, [], 'Save'); // Confirm the targets were again saved correctly and not skipped based on // the previous form value. $view = View::load($id); $header = $view->getDisplay('default')['display_options']['header']; $this->assertEqual(['entity_block', 'entity_entity_test'], array_keys($header)); $this->assertEqual($block->id(), $header['entity_block']['target']); $this->assertEqual($entity_test->uuid(), $header['entity_entity_test']['target']); }
/** * Tests that boolean filter values are updated properly. */ public function testViewsPostUpdateBooleanFilterValues() { $this->runUpdates(); // Load and initialize our test view. $view = View::load('test_boolean_filter_values'); $data = $view->toArray(); // Check that the field is using the expected string value. $this->assertIdentical('1', $data['display']['default']['display_options']['filters']['status']['value']); }
/** * {@inheritdoc} */ public function createView($options = NULL) { if ($view_template = $this->loadTemplate($options)) { $view_template['id'] = $options['id']; $view_template['label'] = $options['label']; $view_template['description'] = $options['description']; return View::create($view_template); } return NULL; }
/** * Tests XSS coming from View block labels. */ protected function doViewTest() { $view = View::create(['id' => $this->randomMachineName(), 'label' => '<script>alert("view");</script>']); $view->addDisplay('block'); $view->save(); $this->drupalGet(Url::fromRoute('block.admin_display')); $this->clickLink('<script>alert("view");</script>'); $this->assertRaw('<script>alert("view");</script>'); $this->assertNoRaw('<script>alert("view");</script>'); }
/** * Tests XSS coming from View block labels. */ protected function doViewTest() { $view = View::create(['id' => $this->randomMachineName(), 'label' => '<script>alert("view");</script>']); $view->addDisplay('block'); $view->save(); $this->drupalGet(Url::fromRoute('block.admin_display')); $this->clickLinkPartialName('Place block'); // The block admin label is automatically XSS admin filtered. $this->assertRaw('alert("view");'); $this->assertNoRaw('<script>alert("view");</script>'); }
/** * Tests that field handlers are updated properly. */ public function testViewsUpdate8004() { $this->runUpdates(); // Load and initialize our test view. $view = View::load('test_duplicate_field_handlers'); $data = $view->toArray(); // Check that the field is using the expected base table. $this->assertEqual('node_field_data', $data['display']['default']['display_options']['fields']['nid']['table']); $this->assertEqual('node_field_data', $data['display']['default']['display_options']['filters']['type']['table']); $this->assertEqual('node_field_data', $data['display']['default']['display_options']['sorts']['vid']['table']); $this->assertEqual('node_field_data', $data['display']['default']['display_options']['arguments']['nid']['table']); }
/** * Tests most of the handlers. */ public function testHandlers() { $this->drupalCreateContentType(array('type' => 'article')); $this->addDefaultCommentField('node', 'article'); $object_types = array_keys(ViewExecutable::getHandlerTypes()); foreach ($this->container->get('views.views_data')->get() as $base_table => $info) { if (!isset($info['table']['base'])) { continue; } $view = View::create(array('base_table' => $base_table)); $view = $view->getExecutable(); // @todo The groupwise relationship is currently broken. $exclude[] = 'taxonomy_term_field_data:tid_representative'; $exclude[] = 'users_field_data:uid_representative'; // Go through all fields and there through all handler types. foreach ($info as $field => $field_info) { // Table is a reserved key for the metainformation. if ($field != 'table' && !in_array("{$base_table}:{$field}", $exclude)) { $item = array('table' => $base_table, 'field' => $field); foreach ($object_types as $type) { if (isset($field_info[$type]['id'])) { $options = array(); if ($type == 'filter') { $handler = $this->container->get("plugin.manager.views.{$type}")->getHandler($item); // Set the value to use for the filter based on the filter type. if ($handler instanceof InOperator) { $options['value'] = array(1); } else { $options['value'] = 1; } } $view->addHandler('default', $type, $base_table, $field, $options); } } } } // Go through each step individually to see whether some parts are // failing. $view->build(); $view->preExecute(); $view->execute(); $view->render(); // Make sure all handlers extend the HandlerBase. foreach ($object_types as $type) { if (isset($view->{$type})) { foreach ($view->{$type} as $handler) { $this->assertTrue($handler instanceof HandlerBase, format_string('@type handler of class %class is an instance of HandlerBase', array('@type' => $type, '%class' => get_class($handler)))); } } } } }
/** * Tests the title area handler. */ public function testTitleText() { $this->drupalGet('test-area-title'); $this->assertTitle('test_title_header | Drupal'); // Check the view to return no result. /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_area_title'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['id'] = ['field' => 'id', 'id' => 'id', 'table' => 'views_test_data', 'relationship' => 'none', 'plugin_id' => 'numeric', 'provider' => 'views_test_data', 'value' => ['value' => '042118160112']]; $view->save(); $this->drupalGet('test-area-title'); $this->assertTitle('test_title_empty | Drupal'); }
/** * Creates a feed and checks that feed's page. */ public function testFeedPage() { // Increase the number of items published in the rss.xml feed so we have // enough articles to test paging. $view = View::load('frontpage'); $display =& $view->getDisplay('feed_1'); $display['display_options']['pager']['options']['items_per_page'] = 30; $view->save(); // Create a feed with 30 items. $this->createSampleNodes(30); $feed = $this->createFeed(); $this->updateFeedItems($feed, 30); // Check for presence of an aggregator pager. $this->drupalGet('aggregator'); $elements = $this->xpath("//ul[contains(@class, :class)]", array(':class' => 'pager__items')); $this->assertTrue(!empty($elements), 'Individual source page contains a pager.'); // Check for sources page title. $this->drupalGet('aggregator/sources'); $titles = $this->xpath('//h1[normalize-space(text())=:title]', array(':title' => 'Sources')); $this->assertTrue(!empty($titles), 'Source page contains correct title.'); // Find the expected read_more link on the sources page. $href = $feed->url(); $links = $this->xpath('//a[@href = :href]', array(':href' => $href)); $this->assertTrue(isset($links[0]), SafeMarkup::format('Link to href %href found.', array('%href' => $href))); $cache_tags_header = $this->drupalGetHeader('X-Drupal-Cache-Tags'); $cache_tags = explode(' ', $cache_tags_header); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); // Check the rss aggregator page as anonymous user. $this->drupalLogout(); $this->drupalGet('aggregator/rss'); $this->assertResponse(403); // Check the rss aggregator page as admin. $this->drupalLogin($this->adminUser); $this->drupalGet('aggregator/rss'); $this->assertResponse(200); $this->assertEqual($this->drupalGetHeader('Content-type'), 'application/rss+xml; charset=utf-8'); // Check the opml aggregator page. $this->drupalGet('aggregator/opml'); $outline = $this->xpath('//outline[1]'); $this->assertEqual($outline[0]['type'], 'rss', 'The correct type attribute is used for rss OPML.'); $this->assertEqual($outline[0]['text'], $feed->label(), 'The correct text attribute is used for rss OPML.'); $this->assertEqual($outline[0]['xmlurl'], $feed->getUrl(), 'The correct xmlUrl attribute is used for rss OPML.'); // Check for the presence of a pager. $this->drupalGet('aggregator/sources/' . $feed->id()); $elements = $this->xpath("//ul[contains(@class, :class)]", array(':class' => 'pager__items')); $this->assertTrue(!empty($elements), 'Individual source page contains a pager.'); $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags')); $this->assertTrue(in_array('aggregator_feed:' . $feed->id(), $cache_tags)); $this->assertTrue(in_array('aggregator_feed_view', $cache_tags)); $this->assertTrue(in_array('aggregator_item_view', $cache_tags)); }
/** * Tests post update function fixes dependencies. * * @see views_post_update_taxonomy_index_tid() */ public function testPostUpdateFunction() { /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_filter_taxonomy_index_tid__non_existing_dependency'); // Dependencies are sorted. $content_dependencies = [$this->terms[3]->getConfigDependencyName(), $this->terms[4]->getConfigDependencyName()]; sort($content_dependencies); $this->assertEqual(['config' => ['taxonomy.vocabulary.tags'], 'content' => $content_dependencies, 'module' => ['node', 'taxonomy', 'user']], $view->calculateDependencies()->getDependencies()); $this->terms[3]->delete(); \Drupal::moduleHandler()->loadInclude('views', 'post_update.php'); views_post_update_taxonomy_index_tid(); $view = View::load('test_filter_taxonomy_index_tid__non_existing_dependency'); $this->assertEqual(['config' => ['taxonomy.vocabulary.tags'], 'content' => [$this->terms[4]->getConfigDependencyName()], 'module' => ['node', 'taxonomy', 'user']], $view->getDependencies()); }
/** * {@inheritdoc} */ public function serialize() { return serialize([ // Only serialize the storage entity ID. $this->storage->id(), $this->current_display, $this->args, $this->current_page, $this->exposed_input, $this->exposed_raw_input, $this->exposed_data, $this->dom_id, $this->executed, ]); }
/** * Tests the updating of views dependencies to image styles. */ public function testUpdateImageStyleDependencies() { $config_dependencies = View::load('foo')->getDependencies()['config']; // Checks that 'thumbnail' image style is not a dependency of view 'foo'. $this->assertFalse(in_array('image.style.thumbnail', $config_dependencies)); // We test the case the the field formatter image style doesn't exist. // Checks that 'nonexistent' image style is not a dependency of view 'foo'. $this->assertFalse(in_array('image.style.nonexistent', $config_dependencies)); // Run updates. $this->runUpdates(); $config_dependencies = View::load('foo')->getDependencies()['config']; // Checks that 'thumbnail' image style is a dependency of view 'foo'. $this->assertTrue(in_array('image.style.thumbnail', $config_dependencies)); // The 'nonexistent' style doesn't exist, thus is not a dependency. Checks // that 'nonexistent' image style is a not dependency of view 'foo'. $this->assertFalse(in_array('image.style.nonexistent', $config_dependencies)); }
/** * Tests query plugins settings. */ public function testQueryUI() { $view = View::load('test_view'); $display =& $view->getDisplay('default'); $display['display_options']['query'] = ['type' => 'query_test']; $view->save(); // Save some query settings. $query_settings_path = "admin/structure/views/nojs/display/test_view/default/query"; $random_value = $this->randomMachineName(); $this->drupalPostForm($query_settings_path, array('query[options][test_setting]' => $random_value), t('Apply')); $this->drupalPostForm(NULL, array(), t('Save')); // Check that the settings are saved into the view itself. $view = Views::getView('test_view'); $view->initDisplay(); $view->initQuery(); $this->assertEqual($random_value, $view->query->options['test_setting'], 'Query settings got saved'); }
/** * @covers ::calculateDependencies */ public function testCalculateDepenencies() { /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_serializer_display_entity'); $display =& $view->getDisplay('rest_export_1'); $display['display_options']['defaults']['style'] = FALSE; $display['display_options']['style']['type'] = 'serializer'; $display['display_options']['style']['options']['formats'] = ['json', 'xml']; $view->save(); $view->calculateDependencies(); $this->assertEquals(['module' => ['rest', 'serialization', 'user']], $view->getDependencies()); \Drupal::service('module_installer')->install(['hal']); $view = View::load('test_serializer_display_entity'); $display =& $view->getDisplay('rest_export_1'); $display['display_options']['style']['options']['formats'] = ['json', 'xml', 'hal_json']; $view->save(); $view->calculateDependencies(); $this->assertEquals(['module' => ['hal', 'rest', 'serialization', 'user']], $view->getDependencies()); }
/** * Tests that role filter dependencies are calculated correctly. */ public function testDependencies() { $role = Role::create(['id' => 'test_user_role']); $role->save(); $view = View::load('test_user_name'); $expected = ['module' => ['user']]; $this->assertEqual($expected, $view->getDependencies()); $display =& $view->getDisplay('default'); $display['display_options']['filters']['roles_target_id'] = ['id' => 'roles_target_id', 'table' => 'user__roles', 'field' => 'roles_target_id', 'value' => ['test_user_role' => 'test_user_role'], 'plugin_id' => 'user_roles']; $view->save(); $expected['config'][] = 'user.role.test_user_role'; $this->assertEqual($expected, $view->getDependencies()); $view = View::load('test_user_name'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['roles_target_id'] = ['id' => 'roles_target_id', 'table' => 'user__roles', 'field' => 'roles_target_id', 'value' => [], 'plugin_id' => 'user_roles']; $view->save(); unset($expected['config']); $this->assertEqual($expected, $view->getDependencies()); }
/** * Ensures that %1 and !1 are converted to twig tokens in existing views. */ public function testArgumentPlaceholderUpdate() { $this->runUpdates(); $view = View::load('test_token_view'); $data = $view->toArray(); $this->assertEqual('{{ arguments.nid }}-test-class-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['style']['options']['col_class_custom']); $this->assertEqual('{{ arguments.nid }}-test-class-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['style']['options']['row_class_custom']); $this->assertEqual('{{ arguments.nid }}-description-{{ raw_arguments.nid }}', $data['display']['feed_1']['display_options']['style']['options']['description']); $this->assertEqual('{{ arguments.nid }}-custom-text-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['fields']['title']['alter']['text']); $this->assertEqual('test_token_view {{ arguments.nid }} {{ raw_arguments.nid }}', $data['display']['default']['display_options']['title']); $this->assertEqual('{{ arguments.nid }}-custom-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['header']['area_text_custom']['content']); $this->assertEqual('{{ arguments.nid }}-text-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['footer']['area']['content']['value']); $this->assertEqual("Displaying @start - @end of @total\n\n{{ arguments.nid }}-result-{{ raw_arguments.nid }}", $data['display']['default']['display_options']['empty']['result']['content']); $this->assertEqual('{{ arguments.nid }}-title-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['empty']['title']['title']); $this->assertEqual('{{ arguments.nid }}-entity-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['empty']['entity_node']['target']); $this->assertEqual('{{ arguments.nid }} title {{ raw_arguments.nid }}', $data['display']['default']['display_options']['arguments']['nid']['title']); $this->assertEqual('{{ arguments.nid }} exception-title {{ raw_arguments.nid }}', $data['display']['default']['display_options']['arguments']['nid']['exception']['title']); $this->assertEqual('{{ arguments.nid }}-more-text-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['use_more_text']); $this->assertEqual('{{ arguments.nid }}-custom-url-{{ raw_arguments.nid }}', $data['display']['default']['display_options']['link_url']); }
/** * Tests that the views list does not use a pager. */ public function testViewsListLimit() { // Check if we can access the main views admin page. $this->drupalGet('admin/structure/views'); $this->assertResponse(200); $this->assertLink(t('Add view')); // Count default views to be subtracted from the limit. $views = count(Views::getEnabledViews()); // Create multiples views. $limit = 51; $values = $this->config('views.view.test_view_storage')->get(); for ($i = 1; $i <= $limit - $views; $i++) { $values['id'] = 'test_view_storage_new' . $i; unset($values['uuid']); $created = View::create($values); $created->save(); } $this->drupalGet('admin/structure/views'); // Check that all the rows are listed. $this->assertEqual(count($this->xpath('//tbody/tr[contains(@class,"views-ui-list-enabled")]')), $limit); }
/** * Tests the views_ui_autocomplete_tag function. */ public function testViewsUiAutocompleteTag() { \Drupal::moduleHandler()->loadInclude('views_ui', 'inc', 'admin'); // Save 15 views with a tag. $tags = array(); for ($i = 0; $i < 16; $i++) { $suffix = $i % 2 ? 'odd' : 'even'; $tag = 'autocomplete_tag_test_' . $suffix . $this->randomMachineName(); $tags[] = $tag; View::create(array('tag' => $tag, 'id' => $this->randomMachineName()))->save(); } // Make sure just ten results are returns. $controller = ViewsUIController::create($this->container); $request = $this->container->get('request_stack')->getCurrentRequest(); $request->query->set('q', 'autocomplete_tag_test'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent(), TRUE); $this->assertEqual(count($matches), 10, 'Make sure the maximum amount of tag results is 10.'); // Make sure the returned array has the proper format. $suggestions = array_map(function ($tag) { return array('value' => $tag, 'label' => Html::escape($tag)); }, $tags); foreach ($matches as $match) { $this->assertTrue(in_array($match, $suggestions), 'Make sure the returned array has the proper format.'); } // Make sure that matching by a certain prefix works. $request->query->set('q', 'autocomplete_tag_test_even'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent(), TRUE); $this->assertEqual(count($matches), 8, 'Make sure that only a subset is returned.'); foreach ($matches as $tag) { $this->assertTrue(array_search($tag['value'], $tags) !== FALSE, format_string('Make sure the returned tag @tag actually exists.', array('@tag' => $tag['value']))); } // Make sure an invalid result doesn't return anything. $request->query->set('q', $this->randomMachineName()); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 0, "Make sure an invalid tag doesn't return anything."); }
/** * Tests integration with image module. */ public function testImage() { /** @var \Drupal\image\ImageStyleInterface $style */ $style = ImageStyle::create(['name' => 'foo']); $style->save(); // Create a new image field 'bar' to be used in 'entity_test_fields' view. FieldStorageConfig::create(['entity_type' => 'entity_test', 'field_name' => 'bar', 'type' => 'image'])->save(); FieldConfig::create(['entity_type' => 'entity_test', 'bundle' => 'entity_test', 'field_name' => 'bar'])->save(); /** @var \Drupal\views\ViewEntityInterface $view */ $view = View::load('entity_test_fields'); $display =& $view->getDisplay('default'); // Add the 'bar' image field to 'entity_test_fields' view. $display['display_options']['fields']['bar'] = ['id' => 'bar', 'field' => 'bar', 'plugin_id' => 'field', 'table' => 'entity_test__bar', 'entity_type' => 'entity_test', 'entity_field' => 'bar', 'type' => 'image', 'settings' => ['image_style' => 'foo', 'image_link' => '']]; $view->save(); $dependencies = $view->getDependencies() + ['config' => []]; // Checks that style 'foo' is a dependency of view 'entity_test_fields'. $this->assertTrue(in_array('image.style.foo', $dependencies['config'])); // Delete the 'foo' image style. $style->delete(); // Checks that the view has been deleted too. $this->assertNull(View::load('entity_test_fields')); }
/** * @covers ::buildResponse */ public function testBuildResponse() { /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_serializer_display_entity'); $display =& $view->getDisplay('rest_export_1'); $display['display_options']['defaults']['style'] = FALSE; $display['display_options']['style']['type'] = 'serializer'; $display['display_options']['style']['options']['formats'] = ['json', 'xml']; $view->save(); // No custom header should be set yet. $response = RestExport::buildResponse('test_serializer_display_entity', 'rest_export_1', []); $this->assertFalse($response->headers->get('Custom-Header')); // Clear render cache. /** @var \Drupal\Core\Cache\MemoryBackend $render_cache */ $render_cache = $this->container->get('cache_factory')->get('render'); $render_cache->deleteAll(); // A custom header should now be added. // @see rest_test_views_views_post_execute() $header = $this->randomString(); $this->container->get('state')->set('rest_test_views_set_header', $header); $response = RestExport::buildResponse('test_serializer_display_entity', 'rest_export_1', []); $this->assertEquals($header, $response->headers->get('Custom-Header')); }
/** * Tests the title area handler. */ public function testTitleText() { // Confirm that the view has the normal title before making the view return // no result. $this->drupalGet('test-area-title'); $this->assertTitle('test_title_header | Drupal'); // Change the view to return no result. /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_area_title'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['name'] = ['field' => 'name', 'id' => 'name', 'table' => 'views_test_data', 'relationship' => 'none', 'plugin_id' => 'string', 'value' => 'Euler']; $view->save(); $this->drupalGet('test-area-title'); $this->assertTitle('test_title_empty | Drupal'); // Change the view to return a result instead. /** @var \Drupal\views\Entity\View $view */ $view = View::load('test_area_title'); $display =& $view->getDisplay('default'); $display['display_options']['filters']['name'] = ['field' => 'name', 'id' => 'name', 'table' => 'views_test_data', 'relationship' => 'none', 'plugin_id' => 'string', 'value' => 'Ringo']; $view->save(); $this->drupalGet('test-area-title'); $this->assertTitle('test_title_header | Drupal'); }
/** * Test table fields in columns. */ public function testFieldInColumns() { $this->drupalGet('test-table'); // Ensure that both columns are in separate tds. // Check for class " views-field-job ", because just "views-field-job" won't // do: "views-field-job-1" would also contain "views-field-job". // @see Drupal\system\Tests\Form\ElementTest::testButtonClasses(). $result = $this->xpath('//tbody/tr/td[contains(concat(" ", @class, " "), " views-field-job ")]'); $this->assertTrue(count($result), 'Ensure there is a td with the class views-field-job'); $result = $this->xpath('//tbody/tr/td[contains(concat(" ", @class, " "), " views-field-job-1 ")]'); $this->assertTrue(count($result), 'Ensure there is a td with the class views-field-job-1'); // Combine the second job-column with the first one, with ', ' as separator. $view = View::load('test_table'); $display =& $view->getDisplay('default'); $display['display_options']['style']['options']['columns']['job_1'] = 'job'; $display['display_options']['style']['options']['info']['job']['separator'] = ', '; $view->save(); // Ensure that both columns are properly combined. $this->drupalGet('test-table'); $result = $this->xpath('//tbody/tr/td[contains(concat(" ", @class, " "), " views-field-job views-field-job-1 ")]'); $this->assertTrue(count($result), 'Ensure that the job column class names are joined into a single column'); $result = $this->xpath('//tbody/tr/td[contains(., "Drummer, Drummer")]'); $this->assertTrue(count($result), 'Ensure the job column values are joined into a single column'); }
/** * Tests REST export with views render caching enabled. */ public function testRestRenderCaching() { $this->drupalLogin($this->adminUser); /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */ $render_cache = \Drupal::service('render_cache'); // Enable render caching for the views. /** @var \Drupal\views\ViewEntityInterface $storage */ $storage = View::load('test_serializer_display_entity'); $options =& $storage->getDisplay('default'); $options['display_options']['cache'] = ['type' => 'tag']; $storage->save(); $original = DisplayPluginBase::buildBasicRenderable('test_serializer_display_entity', 'rest_export_1'); // Ensure that there is no corresponding render cache item yet. $original['#cache'] += ['contexts' => []]; $original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container->getParameter('renderer.config')['required_cache_contexts']); $cache_tags = ['config:views.view.test_serializer_display_entity', 'entity_test:1', 'entity_test:10', 'entity_test:2', 'entity_test:3', 'entity_test:4', 'entity_test:5', 'entity_test:6', 'entity_test:7', 'entity_test:8', 'entity_test:9', 'entity_test_list']; $cache_contexts = ['entity_test_view_grants', 'languages:language_interface', 'theme', 'request_format']; $this->assertFalse($render_cache->get($original)); // Request the page, once in XML and once in JSON to ensure that the caching // varies by it. $result1 = $this->drupalGetJSON('test/serialize/entity'); $this->addRequestWithFormat('json'); $this->assertHeader('content-type', 'application/json'); $this->assertCacheContexts($cache_contexts); $this->assertCacheTags($cache_tags); $this->assertTrue($render_cache->get($original)); $result_xml = $this->drupalGetWithFormat('test/serialize/entity', 'xml'); $this->addRequestWithFormat('xml'); $this->assertHeader('content-type', 'text/xml; charset=UTF-8'); $this->assertCacheContexts($cache_contexts); $this->assertCacheTags($cache_tags); $this->assertTrue($render_cache->get($original)); // Ensure that the XML output is different from the JSON one. $this->assertNotEqual($result1, $result_xml); // Ensure that the cached page works. $result2 = $this->drupalGetJSON('test/serialize/entity'); $this->addRequestWithFormat('json'); $this->assertHeader('content-type', 'application/json'); $this->assertEqual($result2, $result1); $this->assertCacheContexts($cache_contexts); $this->assertCacheTags($cache_tags); $this->assertTrue($render_cache->get($original)); // Create a new entity and ensure that the cache tags are taken over. EntityTest::create(['name' => 'test_11', 'user_id' => $this->adminUser->id()])->save(); $result3 = $this->drupalGetJSON('test/serialize/entity'); $this->addRequestWithFormat('json'); $this->assertHeader('content-type', 'application/json'); $this->assertNotEqual($result3, $result2); // Add the new entity cache tag and remove the first one, because we just // show 10 items in total. $cache_tags[] = 'entity_test:11'; unset($cache_tags[array_search('entity_test:1', $cache_tags)]); $this->assertCacheContexts($cache_contexts); $this->assertCacheTags($cache_tags); $this->assertTrue($render_cache->get($original)); }
/** * Tests the calculation of the rendered dependencies. */ public function doTestCalculateDependencies() { $view = View::load('test_entity_area'); $dependencies = $view->calculateDependencies()->getDependencies(); // Ensure that both config and content entity dependencies are calculated. $this->assertEqual(['config' => ['block.block.test_block'], 'content' => ['entity_test:entity_test:aa0c61cb-b7bb-4795-972a-493dabcf529c']], $dependencies); }
/** * Ensures that the config dependencies are calculated the right way. * * @param \Drupal\views\Entity\View $storage */ protected function assertConfigDependencies(View $storage) { $storage->calculateDependencies(); $this->assertEqual(['config' => ['core.entity_view_mode.entity_test.foobar'], 'module' => ['entity_test']], $storage->getDependencies()); }
/** * Tests the relationship ui for field/filter/argument/relationship. */ public function testRelationshipUI() { $views_admin = $this->drupalCreateUser(array('administer views')); $this->drupalLogin($views_admin); // Make sure the link to the field options exists. $handler_options_path = 'admin/structure/views/nojs/handler/test_handler_relationships/default/field/title'; $view_edit_path = 'admin/structure/views/view/test_handler_relationships/edit'; $this->drupalGet($view_edit_path); $this->assertLinkByHref($handler_options_path); // The test view has a relationship to node_revision so the field should // show a relationship selection. $this->drupalGet($handler_options_path); $relationship_name = 'options[relationship]'; $this->assertFieldByName($relationship_name); // Check for available options. $xpath = $this->constructFieldXpath('name', $relationship_name); $fields = $this->xpath($xpath); $options = array(); foreach ($fields as $field) { $items = $this->getAllOptions($field); foreach ($items as $item) { $options[] = $item->attributes()->value; } } $expected_options = array('none', 'nid'); $this->assertEqual($options, $expected_options); // Remove the relationship and make sure no relationship option appears. $this->drupalPostForm('admin/structure/views/nojs/handler/test_handler_relationships/default/relationship/nid', array(), t('Remove')); $this->drupalGet($handler_options_path); $this->assertNoFieldByName($relationship_name, NULL, 'Make sure that no relationship option is available'); // Create a view of comments with node relationship. View::create(['base_table' => 'comment_field_data', 'id' => 'test_get_entity_type'])->save(); $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_get_entity_type/default/relationship', ['name[comment_field_data.node]' => 'comment_field_data.node'], t('Add and configure relationships')); $this->drupalPostForm(NULL, [], t('Apply')); // Add a content type filter. $this->drupalPostForm('admin/structure/views/nojs/add-handler/test_get_entity_type/default/filter', ['name[node_field_data.type]' => 'node_field_data.type'], t('Add and configure filter criteria')); $this->assertOptionSelected('edit-options-relationship', 'node'); $this->drupalPostForm(NULL, ['options[value][page]' => 'page'], t('Apply')); // Check content type filter options. $this->drupalGet('admin/structure/views/nojs/handler/test_get_entity_type/default/filter/type'); $this->assertOptionSelected('edit-options-relationship', 'node'); $this->assertFieldChecked('edit-options-value-page'); }
/** * @param \Drupal\views\Entity\View $view * @return array */ protected function viewDisplayList(View $view) { $displayManager = $this->getViewDisplayManager(); $displays = array(); foreach ($view->get('display') as $display) { $definition = $displayManager->getDefinition($display['display_plugin']); if (!empty($definition['admin'])) { // Cast the admin label to a string since it is an object. $displays[$definition['id']]['name'] = (string) $definition['admin']; $displays[$definition['id']]['description'] = (string) $definition['help']; } } asort($displays); return $displays; }