/** * Tests the user uid filter and argument. */ public function testUserUid() { $map = array('nid' => 'nid', 'title' => 'title'); $expected = array(array('nid' => $this->node->id(), 'title' => $this->node->label())); $view = Views::getView('test_tracker_user_uid'); $this->executeView($view); // We should have no results as the filter is set for uid 0. $this->assertIdenticalResultSet($view, array(), $map); $view->destroy(); // Change the filter value to our user. $view->initHandlers(); $view->filter['uid_touch_tracker']->value = $this->node->getOwnerId(); $this->executeView($view); // We should have one result as the filter is set for the created user. $this->assertIdenticalResultSet($view, $expected, $map); $view->destroy(); // Remove the filter now, so only the argument will affect the query. $view->removeHandler('default', 'filter', 'uid_touch_tracker'); // Test the incorrect argument UID. $view->initHandlers(); $this->executeView($view, array(rand())); $this->assertIdenticalResultSet($view, array(), $map); $view->destroy(); // Test the correct argument UID. $view->initHandlers(); $this->executeView($view, array($this->node->getOwnerId())); $this->assertIdenticalResultSet($view, $expected, $map); }
/** * Tests the integration. */ public function testIntegration() { // Remove the watchdog entries added by the potential batch process. $this->container->get('database')->truncate('watchdog')->execute(); $entries = array(); // Setup a watchdog entry without tokens. $entries[] = array('message' => $this->randomMachineName(), 'variables' => array(), 'link' => l('Link', 'node/1')); // Setup a watchdog entry with one token. $entries[] = array('message' => '@token1', 'variables' => array('@token1' => $this->randomMachineName()), 'link' => l('Link', 'node/2')); // Setup a watchdog entry with two tokens. $entries[] = array('message' => '@token1 !token2', 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName()), 'link' => l('<object>Link</object>', 'node/2', array('html' => TRUE))); foreach ($entries as $entry) { $entry += array('type' => 'test-views', 'severity' => WATCHDOG_NOTICE); watchdog($entry['type'], $entry['message'], $entry['variables'], $entry['severity'], $entry['link']); } $view = Views::getView('test_dblog'); $this->executeView($view); $view->initStyle(); foreach ($entries as $index => $entry) { $this->assertEqual($view->style_plugin->getField($index, 'message'), String::format($entry['message'], $entry['variables'])); $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['link'])); } // Disable replacing variables and check that the tokens aren't replaced. $view->destroy(); $view->initHandlers(); $this->executeView($view); $view->initStyle(); $view->field['message']->options['replace_variables'] = FALSE; foreach ($entries as $index => $entry) { $this->assertEqual($view->style_plugin->getField($index, 'message'), $entry['message']); } }
/** * Tests the calculateDependencies method. */ public function testCalculateDependencies() { $comment_type = entity_create('comment_type', array('id' => 'comment', 'label' => 'Comment settings', 'description' => 'Comment settings', 'target_entity_type_id' => 'node')); $comment_type->save(); $content_type = entity_create('node_type', array('type' => $this->randomMachineName(), 'name' => $this->randomString())); $content_type->save(); $field_storage = entity_create('field_storage_config', array('field_name' => Unicode::strtolower($this->randomMachineName()), 'entity_type' => 'node', 'type' => 'comment')); $field_storage->save(); entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_label', 'description' => $this->randomMachineName() . '_description', 'settings' => array('comment_type' => $comment_type->id())))->save(); entity_create('field_config', array('field_storage' => FieldStorageConfig::loadByName('node', 'body'), 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_body', 'settings' => array('display_summary' => TRUE)))->save(); $expected = []; $expected['test_field_get_entity'] = ['module' => ['comment', 'node', 'user']]; // Tests dependencies of relationships. $expected['test_relationship_dependency'] = ['module' => ['comment', 'node', 'user']]; $expected['test_plugin_dependencies'] = ['module' => ['comment', 'views_test_data'], 'content' => ['RowTest', 'StaticTest', 'StyleTest']]; $expected['test_argument_dependency'] = ['config' => ['core.entity_view_mode.node.teaser', 'field.storage.node.body'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['node', 'search', 'text', 'user']]; foreach ($this::$testViews as $view_id) { $view = Views::getView($view_id); $dependencies = $view->calculateDependencies(); $this->assertEqual($expected[$view_id], $dependencies); $config = $this->config('views.view.' . $view_id); \Drupal::service('config.storage.staging')->write($view_id, $config->get()); } // Ensure that dependencies are calculated on the display level. $expected_display['default'] = ['config' => ['core.entity_view_mode.node.teaser'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['core', 'node', 'search', 'user', 'views']]; $expected_display['page'] = ['config' => ['field.storage.node.body'], 'module' => ['core', 'text', 'views']]; $view = Views::getView('test_argument_dependency'); $view->initDisplay(); foreach ($view->displayHandlers as $display) { // Calculate the dependencies each display has. $this->assertEqual($expected_display[$display->getPluginId()], $display->calculateDependencies()); } }
/** * 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'); }
/** * Tests the hooks. */ public function testHooks() { $view = Views::getView('test_view'); $view->setDisplay(); // Test each hook is found in the implementations array and is invoked. foreach (static::$hooks as $hook => $type) { $this->assertTrue($this->moduleHandler->implementsHook('views_test_data', $hook), format_string('The hook @hook was registered.', array('@hook' => $hook))); if ($hook == 'views_post_render') { $this->moduleHandler->invoke('views_test_data', $hook, array($view, &$view->display_handler->output, $view->display_handler->getPlugin('cache'))); continue; } switch ($type) { case 'view': $this->moduleHandler->invoke('views_test_data', $hook, array($view)); break; case 'alter': $data = array(); $this->moduleHandler->invoke('views_test_data', $hook, array($data)); break; default: $this->moduleHandler->invoke('views_test_data', $hook); } $this->assertTrue($this->container->get('state')->get('views_hook_test_' . $hook), format_string('The %hook hook was invoked.', array('%hook' => $hook))); // Reset the module implementations cache, so we ensure that the // .views.inc file is loaded actively. $this->moduleHandler->resetImplementations(); } }
/** * Tests file extension views field handler extension_detect_tar option. */ public function testFileExtensionTarOption() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $view = Views::getView('file_extension_view'); $view->setDisplay(); $this->executeView($view); // Test without the tar option. $renderer->executeInRenderContext(new RenderContext(), function () use($view) { $this->assertEqual($view->field['extension']->advancedRender($view->result[0]), 'png'); $this->assertEqual($view->field['extension']->advancedRender($view->result[1]), 'tar'); $this->assertEqual($view->field['extension']->advancedRender($view->result[2]), 'gz'); $this->assertEqual($view->field['extension']->advancedRender($view->result[3]), ''); }); // Test with the tar option. $view = Views::getView('file_extension_view'); $view->setDisplay(); $view->initHandlers(); $view->field['extension']->options['settings']['extension_detect_tar'] = TRUE; $this->executeView($view); $renderer->executeInRenderContext(new RenderContext(), function () use($view) { $this->assertEqual($view->field['extension']->advancedRender($view->result[0]), 'png'); $this->assertEqual($view->field['extension']->advancedRender($view->result[1]), 'tar'); $this->assertEqual($view->field['extension']->advancedRender($view->result[2]), 'tar.gz'); $this->assertEqual($view->field['extension']->advancedRender($view->result[3]), ''); }); }
function testSimple() { $view = Views::getView('test_view'); $view->setDisplay(); $view->displayHandlers->get('default')->overrideOption('fields', array('counter' => array('id' => 'counter', 'table' => 'views', 'field' => 'counter', 'relationship' => 'none'), 'name' => array('id' => 'name', 'table' => 'views_test_data', 'field' => 'name', 'relationship' => 'none'))); $view->preview(); $counter = $view->style_plugin->getField(0, 'counter'); $this->assertEqual($counter, '1', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 1, '@counter' => $counter))); $counter = $view->style_plugin->getField(1, 'counter'); $this->assertEqual($counter, '2', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 2, '@counter' => $counter))); $counter = $view->style_plugin->getField(2, 'counter'); $this->assertEqual($counter, '3', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 3, '@counter' => $counter))); $view->destroy(); $view->storage->invalidateCaches(); $view->setDisplay(); $rand_start = rand(5, 10); $view->displayHandlers->get('default')->overrideOption('fields', array('counter' => array('id' => 'counter', 'table' => 'views', 'field' => 'counter', 'relationship' => 'none', 'counter_start' => $rand_start), 'name' => array('id' => 'name', 'table' => 'views_test_data', 'field' => 'name', 'relationship' => 'none'))); $view->preview(); $counter = $view->style_plugin->getField(0, 'counter'); $expected_number = 0 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); $counter = $view->style_plugin->getField(1, 'counter'); $expected_number = 1 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); $counter = $view->style_plugin->getField(2, 'counter'); $expected_number = 2 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); }
/** * Test comment field name. */ public function testCommentFieldName() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); $view = Views::getView('test_comment_field_name'); $this->executeView($view); $expected_result = [['cid' => $this->comment->id(), 'field_name' => $this->comment->getFieldName()], ['cid' => $this->customComment->id(), 'field_name' => $this->customComment->getFieldName()]]; $column_map = ['cid' => 'cid', 'comment_field_data_field_name' => 'field_name']; $this->assertIdenticalResultset($view, $expected_result, $column_map); // Test that no data can be rendered. $this->assertIdentical(FALSE, isset($view->field['field_name'])); // Grant permission to properly check view access on render. user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']); $this->container->get('account_switcher')->switchTo(new AnonymousUserSession()); $view = Views::getView('test_comment_field_name'); $this->executeView($view); // Test that data rendered. $output = $renderer->executeInRenderContext(new RenderContext(), function () use($view) { return $view->field['field_name']->advancedRender($view->result[0]); }); $this->assertIdentical($this->comment->getFieldName(), $output); $output = $renderer->executeInRenderContext(new RenderContext(), function () use($view) { return $view->field['field_name']->advancedRender($view->result[1]); }); $this->assertIdentical($this->customComment->getFieldName(), $output); }
/** * Tests the handlers. */ public function testHandlers() { $nodes = array(); $nodes[] = $this->drupalCreateNode(); $nodes[] = $this->drupalCreateNode(); $account = $this->drupalCreateUser(); $this->drupalLogin($account); \Drupal::currentUser()->setAccount($account); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute(); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute(); $column_map = array('nid' => 'nid'); // Test the history field. $view = Views::getView('test_history'); $view->setDisplay('page_1'); $this->executeView($view); $this->assertEqual(count($view->result), 2); $output = $view->preview(); $this->setRawContent(\Drupal::service('renderer')->renderRoot($output)); $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker')); $this->assertEqual(count($result), 1, 'Just one node is marked as new'); // Test the history filter. $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); $this->assertEqual(count($view->result), 1); $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map); }
/** * Tests the calculateDependencies method. */ public function testCalculateDependencies() { $expected = []; $expected['test_field_get_entity'] = ['module' => ['comment', 'node', 'user']]; // Tests dependencies of relationships. $expected['test_relationship_dependency'] = ['module' => ['comment', 'node', 'user']]; $expected['test_plugin_dependencies'] = ['module' => ['comment', 'views_test_data'], 'content' => ['RowTest', 'StaticTest', 'StyleTest']]; $expected['test_argument_dependency'] = ['config' => ['core.entity_view_mode.node.teaser', 'field.storage.node.body'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['node', 'search', 'text', 'user']]; foreach ($this::$testViews as $view_id) { $view = Views::getView($view_id); $dependencies = $view->calculateDependencies(); $this->assertEqual($expected[$view_id], $dependencies); $config = $this->config('views.view.' . $view_id); \Drupal::service('config.storage.staging')->write($view_id, $config->get()); } // Ensure that dependencies are calculated on the display level. $expected_display['default'] = ['config' => ['core.entity_view_mode.node.teaser'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['core', 'node', 'search', 'user', 'views']]; $expected_display['page'] = ['config' => ['field.storage.node.body'], 'module' => ['core', 'text', 'views']]; $view = Views::getView('test_argument_dependency'); $view->initDisplay(); foreach ($view->displayHandlers as $display) { // Calculate the dependencies each display has. $this->assertEqual($expected_display[$display->getPluginId()], $display->calculateDependencies()); } }
public function testUserName() { $this->drupalLogin($this->drupalCreateUser(array('access user profiles'))); $view = Views::getView('test_views_handler_field_user_name'); $this->executeView($view); $view->field['name']->options['link_to_user'] = TRUE; $username = $view->result[0]->users_field_data_name = $this->randomMachineName(); $view->result[0]->users_field_data_uid = 1; $render = $view->field['name']->advancedRender($view->result[0]); $this->assertTrue(strpos($render, $username) !== FALSE, 'If link to user is checked the username should be part of the output.'); $this->assertTrue(strpos($render, 'user/1') !== FALSE, 'If link to user is checked the link to the user should appear as well.'); $view->field['name']->options['link_to_user'] = FALSE; $username = $view->result[0]->users_field_data_name = $this->randomMachineName(); $view->result[0]->users_field_data_uid = 1; $render = $view->field['name']->advancedRender($view->result[0]); $this->assertIdentical($render, $username, 'If the user is not linked the username should be printed out for a normal user.'); $view->result[0]->users_field_data_uid = 0; $anon_name = \Drupal::config('user.settings')->get('anonymous'); $view->result[0]->users_field_data_name = ''; $render = $view->field['name']->advancedRender($view->result[0]); $this->assertIdentical($render, $anon_name, 'For user0 it should use the default anonymous name by default.'); $view->field['name']->options['overwrite_anonymous'] = TRUE; $anon_name = $view->field['name']->options['anonymous_text'] = $this->randomMachineName(); $render = $view->field['name']->advancedRender($view->result[0]); $this->assertIdentical($render, $anon_name, 'For user0 it should use the configured anonymous text if overwrite_anonymous is checked.'); }
/** * Tests changing the style plugin and changing some options of a style. */ public function testStyleUI() { $view_name = 'test_view'; $view_edit_url = "admin/structure/views/view/{$view_name}/edit"; $style_plugin_url = "admin/structure/views/nojs/display/{$view_name}/default/style"; $style_options_url = "admin/structure/views/nojs/display/{$view_name}/default/style_options"; $this->drupalGet($style_plugin_url); $this->assertFieldByName('style[type]', 'default', 'The default style plugin selected in the UI should be unformatted list.'); $edit = array('style[type]' => 'test_style'); $this->drupalPostForm(NULL, $edit, t('Apply')); $this->assertFieldByName('style_options[test_option]', NULL, 'Make sure the custom settings form from the test plugin appears.'); $random_name = $this->randomMachineName(); $edit = array('style_options[test_option]' => $random_name); $this->drupalPostForm(NULL, $edit, t('Apply')); $this->drupalGet($style_options_url); $this->assertFieldByName('style_options[test_option]', $random_name, 'Make sure the custom settings form field has the expected value stored.'); $this->drupalPostForm($view_edit_url, array(), t('Save')); $this->assertLink(t('Test style plugin'), 0, 'Make sure the test style plugin is shown in the UI'); $view = Views::getView($view_name); $view->initDisplay(); $style = $view->display_handler->getOption('style'); $this->assertEqual($style['type'], 'test_style', 'Make sure that the test_style got saved as used style plugin.'); $this->assertEqual($style['options']['test_option'], $random_name, 'Make sure that the custom settings field got saved as expected.'); // Test that fields are working correctly in the UI for style plugins when // a field row plguin is selected. $this->drupalPostForm("admin/structure/views/view/{$view_name}/edit", array(), 'Add Page'); $this->drupalPostForm("admin/structure/views/nojs/display/{$view_name}/page_1/row", array('row[type]' => 'fields'), t('Apply')); // If fields are being used this text will not be shown. $this->assertNoText(t('The selected style or row format does not utilize fields.')); }
/** * View element pre render callback. */ public static function preRenderViewElement($element) { $element['#attributes']['class'][] = 'views-element-container'; if (!isset($element['#view'])) { $view = Views::getView($element['#name']); } else { $view = $element['#view']; } if ($view && $view->access($element['#display_id'])) { if (!empty($element['#embed'])) { $element += $view->preview($element['#display_id'], $element['#arguments']); } else { // Add contextual links to the view. We need to attach them to the dummy // $view_array variable, since contextual_preprocess() requires that they // be attached to an array (not an object) in order to process them. For // our purposes, it doesn't matter what we attach them to, since once they // are processed by contextual_preprocess() they will appear in the // $title_suffix variable (which we will then render in // views-view.html.twig). $view->setDisplay($element['#display_id']); // Add the result of the executed view as a child element so any // #pre_render elements for the view will get processed. A #pre_render // element cannot be added to the main element as this is already inside // a #pre_render callback. $element['view_build'] = $view->executeDisplay($element['#display_id'], $element['#arguments']); if (isset($element['view_build']['#title'])) { $element['#title'] =& $element['view_build']['#title']; } views_add_contextual_links($element, 'view', $view, $view->current_display); } } return $element; }
/** * View element pre render callback. */ public static function preRenderViewElement($element) { $element['#attributes']['class'][] = 'views-element-container'; if (!isset($element['#view'])) { $view = Views::getView($element['#name']); } else { $view = $element['#view']; } if ($view && $view->access($element['#display_id'])) { if (!empty($element['embed'])) { $element += $view->preview($element['#display_id'], $element['#arguments']); } else { // Add contextual links to the view. We need to attach them to the dummy // $view_array variable, since contextual_preprocess() requires that they // be attached to an array (not an object) in order to process them. For // our purposes, it doesn't matter what we attach them to, since once they // are processed by contextual_preprocess() they will appear in the // $title_suffix variable (which we will then render in // views-view.html.twig). $view->setDisplay($element['#display_id']); $element += $view->executeDisplay($element['#display_id'], $element['#arguments']); views_add_contextual_links($element, 'view', $view, $view->current_display); } } return $element; }
/** * Tests changing the row plugin and changing some options of a row. */ public function testRowUI() { $view_name = 'test_view'; $view_edit_url = "admin/structure/views/view/{$view_name}/edit"; $row_plugin_url = "admin/structure/views/nojs/display/{$view_name}/default/row"; $row_options_url = "admin/structure/views/nojs/display/{$view_name}/default/row_options"; $this->drupalGet($row_plugin_url); $this->assertFieldByName('row[type]', 'fields', 'The default row plugin selected in the UI should be fields.'); $edit = array('row[type]' => 'test_row'); $this->drupalPostForm(NULL, $edit, t('Apply')); $this->assertFieldByName('row_options[test_option]', NULL, 'Make sure the custom settings form from the test plugin appears.'); $random_name = $this->randomMachineName(); $edit = array('row_options[test_option]' => $random_name); $this->drupalPostForm(NULL, $edit, t('Apply')); $this->drupalGet($row_options_url); $this->assertFieldByName('row_options[test_option]', $random_name, 'Make sure the custom settings form field has the expected value stored.'); $this->drupalPostForm($view_edit_url, array(), t('Save')); $this->assertLink(t('Test row plugin'), 0, 'Make sure the test row plugin is shown in the UI'); $view = Views::getView($view_name); $view->initDisplay(); $row = $view->display_handler->getOption('row'); $this->assertEqual($row['type'], 'test_row', 'Make sure that the test_row got saved as used row plugin.'); $this->assertEqual($row['options']['test_option'], $random_name, 'Make sure that the custom settings field got saved as expected.'); // Change the row plugin to fields using ajax. $this->drupalPostAjaxForm($row_plugin_url, array('row[type]' => 'fields'), array('op' => 'Apply'), str_replace('/nojs/', '/ajax/', $row_plugin_url)); $this->drupalPostAjaxForm(NULL, array(), array('op' => 'Apply')); $this->assertResponse(200); $this->assertFieldByName('row[type]', 'fields', 'Make sure that the fields got saved as used row plugin.'); }
/** * Tests the glossary feature. */ function testGlossary() { // Setup some nodes, one with a, two with b and three with c. $counter = 1; foreach (array('a', 'b', 'c') as $char) { for ($i = 0; $i < $counter; $i++) { $edit = array('title' => $char . $this->randomMachineName()); $this->drupalCreateNode($edit); } } $view = Views::getView('test_glossary'); $this->executeView($view); $count_field = 'nid'; foreach ($view->result as &$row) { if (strpos($view->field['title']->getValue($row), 'a') === 0) { $this->assertEqual(1, $row->{$count_field}); } if (strpos($view->field['title']->getValue($row), 'b') === 0) { $this->assertEqual(2, $row->{$count_field}); } if (strpos($view->field['title']->getValue($row), 'c') === 0) { $this->assertEqual(3, $row->{$count_field}); } } }
/** * Tests the attachment UI. */ public function testAttachmentUI() { $this->drupalGet('admin/structure/views/view/test_attachment_ui/edit/attachment_1'); $this->assertText(t('Not defined'), 'The right text appears if there is no attachment selection yet.'); $attachment_display_url = 'admin/structure/views/nojs/display/test_attachment_ui/attachment_1/displays'; $this->drupalGet($attachment_display_url); // Display labels should be escaped. $this->assertEscaped('<em>Page</em>'); foreach (array('default', 'page-1') as $display_id) { $this->assertNoFieldChecked("edit-displays-{$display_id}", format_string('Make sure the @display_id can be marked as attached', array('@display_id' => $display_id))); } // Save the attachments and test the value on the view. $this->drupalPostForm($attachment_display_url, array('displays[page_1]' => 1), t('Apply')); // Options summary should be escaped. $this->assertEscaped('<em>Page</em>'); $this->assertNoRaw('<em>Page</em>'); $result = $this->xpath('//a[@id = :id]', array(':id' => 'views-attachment-1-displays')); $this->assertEqual($result[0]->attributes()->title, t('Page')); $this->drupalPostForm(NULL, array(), t('Save')); $view = Views::getView('test_attachment_ui'); $view->initDisplay(); $this->assertEqual(array_keys(array_filter($view->displayHandlers->get('attachment_1')->getOption('displays'))), array('page_1'), 'The attached displays got saved as expected'); $this->drupalPostForm($attachment_display_url, array('displays[default]' => 1, 'displays[page_1]' => 1), t('Apply')); $result = $this->xpath('//a[@id = :id]', array(':id' => 'views-attachment-1-displays')); $this->assertEqual($result[0]->attributes()->title, t('Multiple displays')); $this->drupalPostForm(NULL, array(), t('Save')); $view = Views::getView('test_attachment_ui'); $view->initDisplay(); $this->assertEqual(array_keys($view->displayHandlers->get('attachment_1')->getOption('displays')), array('default', 'page_1'), 'The attached displays got saved as expected'); }
/** * Tests the setting and output of custom labels for boolean values. */ public function testCustomOption() { // Add the boolean field handler to the test view. $view = Views::getView('test_view'); $view->setDisplay(); $view->displayHandlers->get('default')->overrideOption('fields', array('age' => array('id' => 'age', 'table' => 'views_test_data', 'field' => 'age', 'relationship' => 'none'))); $this->executeView($view); $custom_true = 'Yay'; $custom_false = 'Nay'; // Set up some custom value mappings for different types. $custom_values = array('plain' => array('true' => $custom_true, 'false' => $custom_false, 'test' => 'assertTrue'), 'allowed tag' => array('true' => '<p>' . $custom_true . '</p>', 'false' => '<p>' . $custom_false . '</p>', 'test' => 'assertTrue'), 'disallowed tag' => array('true' => '<script>' . $custom_true . '</script>', 'false' => '<script>' . $custom_false . '</script>', 'test' => 'assertFalse')); // Run the same tests on each type. foreach ($custom_values as $type => $values) { $options = array('options[type]' => 'custom', 'options[type_custom_true]' => $values['true'], 'options[type_custom_false]' => $values['false']); $this->drupalPostForm('admin/structure/views/nojs/handler/test_view/default/field/age', $options, 'Apply'); // Save the view. $this->drupalPostForm('admin/structure/views/view/test_view', array(), 'Save'); $view = Views::getView('test_view'); $output = $view->preview(); $output = drupal_render($output); $replacements = array('%type' => $type); $this->{$values['test']}(strpos($output, $values['true']), format_string('Expected custom boolean TRUE value in output for %type.', $replacements)); $this->{$values['test']}(strpos($output, $values['false']), format_string('Expected custom boolean FALSE value in output for %type', $replacements)); } }
/** * Tests the integration. */ public function testIntegration() { // Remove the watchdog entries added by the potential batch process. $this->container->get('database')->truncate('watchdog')->execute(); $entries = array(); // Setup a watchdog entry without tokens. $entries[] = array('message' => $this->randomMachineName(), 'variables' => array('link' => \Drupal::l('Link', new Url('<front>')))); // Setup a watchdog entry with one token. $entries[] = array('message' => '@token1', 'variables' => array('@token1' => $this->randomMachineName(), 'link' => \Drupal::l('Link', new Url('<front>')))); // Setup a watchdog entry with two tokens. $entries[] = array('message' => '@token1 !token2', 'variables' => array('@token1' => $this->randomMachineName(), '!token2' => $this->randomMachineName(), 'link' => \Drupal::l(SafeMarkup::set('<object>Link</object>'), new Url('<front>')))); $logger_factory = $this->container->get('logger.factory'); foreach ($entries as $entry) { $entry += array('type' => 'test-views', 'severity' => RfcLogLevel::NOTICE); $logger_factory->get($entry['type'])->log($entry['severity'], $entry['message'], $entry['variables']); } $view = Views::getView('test_dblog'); $this->executeView($view); $view->initStyle(); foreach ($entries as $index => $entry) { $this->assertEqual($view->style_plugin->getField($index, 'message'), SafeMarkup::format($entry['message'], $entry['variables'])); $this->assertEqual($view->style_plugin->getField($index, 'link'), Xss::filterAdmin($entry['variables']['link'])); } // Disable replacing variables and check that the tokens aren't replaced. $view->destroy(); $view->storage->invalidateCaches(); $view->initHandlers(); $this->executeView($view); $view->initStyle(); $view->field['message']->options['replace_variables'] = FALSE; foreach ($entries as $index => $entry) { $this->assertEqual($view->style_plugin->getField($index, 'message'), $entry['message']); } }
/** * Tests the generic bundle filter. */ public function testFilterEntity() { $view = Views::getView('test_entity_type_filter'); // Tests \Drupal\views\Plugin\views\filter\Bundle::calculateDependencies(). $expected = ['config' => ['node.type.test_bundle', 'node.type.test_bundle_2'], 'module' => ['node']]; $this->assertIdentical($expected, $view->getDependencies()); $this->executeView($view); // Test we have all the results, with all types selected. $this->assertEqual(count($view->result), $this->entities['count']); // Test the valueOptions of the filter handler. $expected = array(); foreach ($this->entityBundles as $key => $info) { $expected[$key] = $info['label']; } $this->assertIdentical($view->filter['type']->getValueOptions(), $expected); $view->destroy(); // Test each bundle type. foreach ($this->entityBundles as $key => $info) { // Test each bundle type. $view->initDisplay(); $filters = $view->display_handler->getOption('filters'); $filters['type']['value'] = array($key => $key); $view->display_handler->setOption('filters', $filters); $this->executeView($view); $this->assertEqual(count($view->result), count($this->entities[$key])); $view->destroy(); } // Test an invalid bundle type to make sure we have no results. $view->initDisplay(); $filters = $view->display_handler->getOption('filters'); $filters['type']['value'] = array('type_3' => 'type_3'); $view->display_handler->setOption('filters', $filters); $this->executeView($view); $this->assertEqual(count($view->result), 0); }
/** * Tests the handlers. */ public function testHandlers() { $nodes = array(); $nodes[] = $this->drupalCreateNode(); $nodes[] = $this->drupalCreateNode(); $account = $this->drupalCreateUser(); $this->drupalLogin($account); \Drupal::currentUser()->setAccount($account); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[0]->id(), 'timestamp' => REQUEST_TIME - 100))->execute(); db_insert('history')->fields(array('uid' => $account->id(), 'nid' => $nodes[1]->id(), 'timestamp' => REQUEST_TIME + 100))->execute(); $column_map = array('nid' => 'nid'); // Test the history field. $view = Views::getView('test_history'); $view->setDisplay('page_1'); $this->executeView($view); $this->assertEqual(count($view->result), 2); $output = $view->preview(); $this->setRawContent(\Drupal::service('renderer')->renderRoot($output)); $result = $this->xpath('//span[@class=:class]', array(':class' => 'marker')); $this->assertEqual(count($result), 1, 'Just one node is marked as new'); // Test the history filter. $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); $this->assertEqual(count($view->result), 1); $this->assertIdenticalResultset($view, array(array('nid' => $nodes[0]->id())), $column_map); // Install Comment module and make sure that content types without comment // field will not break the view. // See \Drupal\history\Plugin\views\filter\HistoryUserTimestamp::query() \Drupal::service('module_installer')->install(['comment']); $view = Views::getView('test_history'); $view->setDisplay('page_2'); $this->executeView($view); }
/** * Tests the integration. */ public function testForumIntegration() { // Create a forum. $entity_manager = $this->container->get('entity.manager'); $term = $entity_manager->getStorage('taxonomy_term')->create(array('vid' => 'forums', 'name' => $this->randomName())); $term->save(); $comment_storage = $entity_manager->getStorage('comment'); // Create some nodes which are part of this forum with some comments. $nodes = array(); for ($i = 0; $i < 3; $i++) { $node = $this->drupalCreateNode(array('type' => 'forum', 'taxonomy_forums' => array($term->id()), 'sticky' => $i == 0 ? NODE_STICKY : NODE_NOT_STICKY)); $nodes[] = $node; } $account = $this->drupalCreateUser(array('skip comment approval')); $this->drupalLogin($account); $comments = array(); foreach ($nodes as $index => $node) { for ($i = 0; $i <= $index; $i++) { $comment = $comment_storage->create(array('entity_type' => 'node', 'entity_id' => $node->id(), 'field_name' => 'comment_forum')); $comment->save(); $comments[$comment->get('entity_id')->target_id][$comment->id()] = $comment; } } $view = Views::getView('test_forum_index'); $this->executeView($view); $expected_result = array(); $expected_result[] = array('nid' => $nodes[0]->id(), 'sticky' => NODE_STICKY, 'comment_count' => 1.0); $expected_result[] = array('nid' => $nodes[1]->id(), 'sticky' => NODE_NOT_STICKY, 'comment_count' => 2.0); $expected_result[] = array('nid' => $nodes[2]->id(), 'sticky' => NODE_NOT_STICKY, 'comment_count' => 3.0); $column_map = array('nid' => 'nid', 'forum_index_sticky' => 'sticky', 'forum_index_comment_count' => 'comment_count'); $this->assertIdenticalResultset($view, $expected_result, $column_map); }
/** * Tests access on render caching. */ public function testRenderCaching() { $view = Views::getView('test_access_role'); $display =& $view->storage->getDisplay('default'); $display['display_options']['cache'] = ['type' => 'tag']; $display['display_options']['access']['options']['role'] = array($this->normalRole => $this->normalRole); $view->save(); /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = \Drupal::service('renderer'); /** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */ $account_switcher = \Drupal::service('account_switcher'); // First access as user with access. $build = DisplayPluginBase::buildBasicRenderable('test_access_role', 'default'); $account_switcher->switchTo($this->normalUser); $result = $renderer->renderPlain($build); $this->assertTrue(in_array('user.roles', $build['#cache']['contexts'])); $this->assertEqual(['config:views.view.test_access_role'], $build['#cache']['tags']); $this->assertEqual(Cache::PERMANENT, $build['#cache']['max-age']); $this->assertNotEqual($result, ''); // Then without access. $build = DisplayPluginBase::buildBasicRenderable('test_access_role', 'default'); $account_switcher->switchTo($this->webUser); $result = $renderer->renderPlain($build); // @todo Fix this in https://www.drupal.org/node/2551037, // DisplayPluginBase::applyDisplayCachablityMetadata() is not invoked when // using buildBasicRenderable() and a Views access plugin returns FALSE. //$this->assertTrue(in_array('user.roles', $build['#cache']['contexts'])); //$this->assertEqual([], $build['#cache']['tags']); $this->assertEqual(Cache::PERMANENT, $build['#cache']['max-age']); $this->assertEqual($result, ''); }
/** * Tests adding a view of media revisions. */ public function testMediaRevisionWizard() { $view = []; $view['label'] = $this->randomMachineName(16); $view['id'] = strtolower($this->randomMachineName(16)); $view['show[wizard_key]'] = 'media_revision'; $view['page[create]'] = TRUE; $view['page[path]'] = $this->randomMachineName(16); // Just triggering the saving should automatically choose a proper row // plugin. $this->drupalPostForm('admin/structure/views/add', $view, t('Save and edit')); $this->assertUrl('admin/structure/views/view/' . $view['id'], [], 'Make sure the view saving was successful and the browser got redirected to the edit page.'); $user = $this->drupalCreateUser(['view all revisions']); $this->drupalLogin($user); $view = Views::getView($view['id']); $view->initHandlers(); $row = $view->display_handler->getOption('row'); $this->assertEqual($row['type'], 'fields'); // Check for the default filters. $this->assertEqual($view->filter['status']->table, 'media_field_revision'); $this->assertEqual($view->filter['status']->field, 'status'); $this->assertTrue($view->filter['status']->value); // Check for the default fields. $this->assertEqual($view->field['name']->table, 'media_field_revision'); $this->assertEqual($view->field['name']->field, 'name'); $this->assertEqual($view->field['changed']->table, 'media_field_revision'); $this->assertEqual($view->field['changed']->field, 'changed'); }
/** * Tests the generated title of an user: uid argument. */ public function testArgumentTitle() { $view = Views::getView('test_user_uid_argument'); // Tests an invalid user uid. $this->executeView($view, array(rand(1000, 10000))); $this->assertFalse($view->getTitle()); $view->destroy(); // Tests a valid user. $account = $this->drupalCreateUser(); $this->executeView($view, array($account->id())); $this->assertEqual($view->getTitle(), $account->label()); $view->destroy(); // Tests the anonymous user. $anonymous = $this->config('user.settings')->get('anonymous'); $this->executeView($view, array(0)); $this->assertEqual($view->getTitle(), $anonymous); $view->destroy(); $view->getDisplay()->getHandler('argument', 'uid')->options['break_phrase'] = TRUE; $this->executeView($view, array($account->id() . ',0')); $this->assertEqual($view->getTitle(), $account->label() . ', ' . $anonymous); $view->destroy(); $view->getDisplay()->getHandler('argument', 'uid')->options['break_phrase'] = TRUE; $this->executeView($view, array('0,' . $account->id())); $this->assertEqual($view->getTitle(), $anonymous . ', ' . $account->label()); $view->destroy(); }
public function testAreaText() { // Test validation $view = Views::getView('test_view'); $view->setDisplay(); // Add a null argument. $view->displayHandlers->get('default')->overrideOption('arguments', array('null' => array('id' => 'null', 'table' => 'views', 'field' => 'null'))); $this->executeView($view); // Make sure that the argument is not validated yet. unset($view->argument['null']->argument_validated); $this->assertTrue($view->argument['null']->validateArgument(26)); // test must_not_be option. unset($view->argument['null']->argument_validated); $view->argument['null']->options['must_not_be'] = TRUE; $this->assertFalse($view->argument['null']->validateArgument(26), 'must_not_be returns FALSE, if there is an argument'); unset($view->argument['null']->argument_validated); $this->assertTrue($view->argument['null']->validateArgument(NULL), 'must_not_be returns TRUE, if there is no argument'); // Test execution. $view->destroy(); $view->setDisplay(); // Add a argument, which has null as handler. $view->displayHandlers->get('default')->overrideOption('arguments', array('id' => array('id' => 'id', 'table' => 'views_test_data', 'field' => 'id'))); $this->executeView($view, array(26)); // The argument should be ignored, so every result should return. $this->assertEqual(5, count($view->result)); }
/** * Tests basic field handler settings in the UI. */ public function testHandlerUI() { $url = "admin/structure/views/nojs/handler/test_view_fieldapi/default/field/field_name_0"; $this->drupalGet($url); // Tests the available formatter options. $result = $this->xpath('//select[@id=:id]/option', array(':id' => 'edit-options-type')); $options = array_map(function ($item) { return (string) $item->attributes()->value[0]; }, $result); // @todo Replace this sort by assertArray once it's in. sort($options, SORT_STRING); $this->assertEqual($options, array('string', 'text_default', 'text_trimmed'), 'The text formatters for a simple text field appear as expected.'); $this->drupalPostForm(NULL, array('options[type]' => 'text_trimmed'), t('Apply')); $this->drupalGet($url); $this->assertOptionSelected('edit-options-type', 'text_trimmed'); $random_number = rand(100, 400); $this->drupalPostForm(NULL, array('options[settings][trim_length]' => $random_number), t('Apply')); $this->drupalGet($url); $this->assertFieldByName('options[settings][trim_length]', $random_number, 'The formatter setting got saved.'); // Save the view and test whether the settings are saved. $this->drupalPostForm('admin/structure/views/view/test_view_fieldapi', array(), t('Save')); $view = Views::getView('test_view_fieldapi'); $view->initHandlers(); $this->assertEqual($view->field['field_name_0']->options['type'], 'text_trimmed'); $this->assertEqual($view->field['field_name_0']->options['settings']['trim_length'], $random_number); }
/** * Tests the getEntity method. */ public function testGetEntity() { // The view is a view of comments, their nodes and their authors, so there // are three layers of entities. $account = entity_create('user', array('name' => $this->randomMachineName(), 'bundle' => 'user')); $account->save(); $this->drupalCreateContentType(array('type' => 'page')); $this->addDefaultCommentField('node', 'page'); $node = entity_create('node', array('uid' => $account->id(), 'type' => 'page')); $node->save(); $comment = entity_create('comment', array('uid' => $account->id(), 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment')); $comment->save(); $view = Views::getView('test_field_get_entity'); $this->executeView($view); $row = $view->result[0]; // Tests entities on the base level. $entity = $view->field['cid']->getEntity($row); $this->assertEqual($entity->id(), $comment->id(), 'Make sure the right comment entity got loaded.'); // Tests entities as relationship on first level. $entity = $view->field['nid']->getEntity($row); $this->assertEqual($entity->id(), $node->id(), 'Make sure the right node entity got loaded.'); // Tests entities as relationships on second level. $entity = $view->field['uid']->getEntity($row); $this->assertEqual($entity->id(), $account->id(), 'Make sure the right user entity got loaded.'); }
public function testFieldBoolean() { $view = Views::getView('test_view'); $view->setDisplay(); $view->displayHandlers->get('default')->overrideOption('fields', array('age' => array('id' => 'age', 'table' => 'views_test_data', 'field' => 'age', 'relationship' => 'none'))); $this->executeView($view); // This is john, which has no age, there are no custom formats defined, yet. $this->assertEqual(t('No'), $view->field['age']->advancedRender($view->result[0])); $this->assertEqual(t('Yes'), $view->field['age']->advancedRender($view->result[1])); // Reverse the output. $view->field['age']->options['not'] = TRUE; $this->assertEqual(t('Yes'), $view->field['age']->advancedRender($view->result[0])); $this->assertEqual(t('No'), $view->field['age']->advancedRender($view->result[1])); unset($view->field['age']->options['not']); // Use another output format. $view->field['age']->options['type'] = 'true-false'; $this->assertEqual(t('False'), $view->field['age']->advancedRender($view->result[0])); $this->assertEqual(t('True'), $view->field['age']->advancedRender($view->result[1])); // test awesome unicode. $view->field['age']->options['type'] = 'unicode-yes-no'; $this->assertEqual('✖', $view->field['age']->advancedRender($view->result[0])); $this->assertEqual('✔', $view->field['age']->advancedRender($view->result[1])); // Set a custom output format. $view->field['age']->formats['test'] = array(t('Test-True'), t('Test-False')); $view->field['age']->options['type'] = 'test'; $this->assertEqual(t('Test-False'), $view->field['age']->advancedRender($view->result[0])); $this->assertEqual(t('Test-True'), $view->field['age']->advancedRender($view->result[1])); }
/** * Tests the title area handler. */ public function testTitleText() { $view = Views::getView('test_area_title'); $view->setDisplay('default'); $this->executeView($view); $view->render(); $this->assertFalse($view->getTitle(), 'The title area does not override the title if the view is not empty.'); $view->destroy(); $view->setDisplay('default'); $this->executeView($view); $view->result = array(); $view->render(); $this->assertEqual($view->getTitle(), 'test_title_empty', 'The title area should override the title if the result is empty.'); $view->destroy(); $view->setDisplay('page_1'); $this->executeView($view); $view->render(); $this->assertEqual($view->getTitle(), 'test_title_header', 'The title area on the header should override the title if the result is not empty.'); $view->destroy(); $view->setDisplay('page_1'); $this->executeView($view); $view->result = array(); $view->render(); $this->assertEqual($view->getTitle(), 'test_title_empty', 'The title area should override the title if the result is empty.'); $view->destroy(); }