improvements-2.x-dev/modules/improvements_views/tests/src/Functional/ImprovementsViewsTest.php

modules/improvements_views/tests/src/Functional/ImprovementsViewsTest.php
<?php

namespace Drupal\Tests\improvements_views\Functional;

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\improvements\Traits\ImprovementsTestTrait;
use Drupal\Tests\node\Traits\NodeCreationTrait;
use Drupal\Tests\taxonomy\Traits\TaxonomyTestTrait;
use Drupal\views\ViewExecutable;

class ImprovementsViewsTest extends BrowserTestBase {

  use ImprovementsTestTrait;
  use NodeCreationTrait;
  use TaxonomyTestTrait;

  /**
   * {@inheritDoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * {@inheritDoc}
   */
  protected static $modules = ['improvements_views'];

  /**
   * {@inheritDoc}
   */
  protected function setUp(): void {
    parent::setUp();
  }

  /**
   * Test "entity_reference_views_formatter" formatter.
   *
   * @covers \Drupal\improvements_views\Plugin\Field\FieldFormatter\EntityReferenceViewsFormatter
   */
  public function testFieldFormatterEntityReferenceViews(): void {
    $this->installModule('node', 'improvements_views_test', 'field', 'field_ui');
    $this->createContentType(['type' => 'page', 'name' => 'Page']);
    $field_name = 'field_views_formatter_test';
    $views_name = 'test_entity_reference_views_formatter';

    $this->createField(
      entity_type: 'node',
      entity_bundle: 'page',
      field_name: $field_name,
      field_type: 'entity_reference',
      field_label: 'Entity reference',
      storage_settings: ['cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED],
      formatter_type: 'entity_reference_views_formatter',
      formatter_options: ['weight' => 0],
    );

    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/types/manage/page/display');
    $this->dontSeeErrorMessage();
    $web_assert = $this->assertSession();
    $web_assert->elementExists('css', 'option[value="entity_reference_views_formatter"][selected]');

    $this->openEntityDisplayComponentSettings($field_name);
    $web_assert->elementExists('css', 'select[name="fields[' . $field_name . '][settings_edit_form][settings][views]"]');
    $web_assert->elementExists('css', 'option[value="' . $views_name . ':default"]');

    $this->submitForm([
      'fields[' . $field_name . '][settings_edit_form][settings][views]' => $views_name . ':default',
    ], 'Save');
    $this->dontSeeErrorMessage();
    $web_assert->pageTextContains('Views: ' . $views_name . ':default');

    $node1 = $this->createNode(['title' => 'Node 1 for test ' . __FUNCTION__]);
    $node2 = $this->createNode(['title' => 'Node 2 for test ' . __FUNCTION__]);
    $node3 = $this->createNode(['title' => 'Node 3 for test ' . __FUNCTION__]);
    $node4 = $this->createNode([
      'title' => 'Node 4 for test ' . __FUNCTION__,
      $field_name => [
        $node1->id(),
        $node2->id(),
      ],
    ]);

    $this->drupalGetEntityPage($node4);
    $web_assert->elementExists('css', '.views-element-container');
    $web_assert->pageTextContains($node1->label());
    $web_assert->pageTextContains($node2->label());
    $web_assert->pageTextNotContains($node3->label());

    $this->drupalGetEntityPage($node3);
    $web_assert->elementNotExists('css', '.views-element-container');
  }

  /**
   * Test Views field plugin "map".
   *
   * @covers \Drupal\improvements_views\Plugin\views\field\Map
   */
  public function testViewsPluginFieldMap(): void {
    $this->installModule('node', 'improvements_views_test');
    $this->createContentType(['type' => 'page', 'name' => 'Page']);
    $node = $this->createNode([
      'title' => 'Node for test ' . __FUNCTION__,
      'test_map_field' => [
        'foo' => [
          'bar' => 'Hello world!',
        ],
      ],
    ]);
    $views_build = views_embed_view('test_views_map_field_plugin');
    $renderer = $this->container->get('renderer');
    $views_output = (string)$renderer->renderRoot($views_build);
    $this->assertStringContainsString('<span class="field-content">Hello world!</span>', $views_output);
  }

  /**
   * Test Views extended numeric filter.
   *
   * @covers \Drupal\improvements_views\Plugin\views\filter\ExtendedNumericFilter
   */
  public function testViewsPluginFilterExtendedNumeric(): void {
    $this->installModule('node', 'views_ui');
    $view_config_entity = $this->createView([
      'id' => 'test_extended_numeric_filter',
      'label' => 'Test extended numeric filter',
      'base_table' => 'node_field_data',
    ]);
    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/views/nojs/add-handler/' . $view_config_entity->id() . '/default/filter');
    $this->dontSeeErrorMessage();
    $this->submitForm(['name[node_field_data.nid]' => TRUE], 'Add and configure filter criteria');
    $this->dontSeeErrorMessage();
    $web_assert = $this->assertSession();
    $web_assert->elementExists('css', 'select[name="options[operator]"] option[value="in"]');

    $this->submitForm([
      'options[operator]' => 'in',
      'options[value][value]' => '1,2,3',
    ], 'Apply');
    $this->dontSeeErrorMessage();

    // @TODO Check generated sql query
  }

  /**
   * Test Views "is_current_user" sort plugin.
   *
   * @covers \Drupal\improvements_views\Plugin\views\sort\IsCurrentUser
   */
  public function testViewsPluginSortIsCurrentUserSort(): void {
    $this->installModule('node', 'user', 'improvements_views_test');

    // Check view exists
    $this->installModule('views_ui');
    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/views/view/test_sort_by_current_user');
    $web_assert = $this->assertSession();
    $web_assert->pageTextContains('Content: Author is current user (asc)');

    \Drupal::getContainer()->get('current_user')->setAccount($this->rootUser);
    $sql = (string)$this->getViewQuery('test_sort_by_current_user');
    $this->assertStringContainsString('IF (node_field_data.uid = 1, ' . $this->rootUser->id() . ', 0) AS "uid_is_current_user"', $sql);
    $this->assertStringContainsString('ORDER BY "uid_is_current_user"', $sql);
  }

  /**
   * Test sort by comment author is current user
   *
   * @covers \Drupal\improvements_views\Plugin\views\sort\IsCurrentUser
   */
  public function testViewsPluginSortByCommentAuthorIsCurrentUser(): void {
    $this->installModule('node', 'comment', 'user', 'improvements_views_test');
    $this->drupalLoginAsRoot();
    \Drupal::getContainer()->get('current_user')->setAccount($this->rootUser);
    $sql = (string)$this->getViewQuery('test_sort_by_comment_author_is_current_user');
    $this->assertStringContainsString('IF (comment_field_data.uid = 1, ' . $this->rootUser->id() . ', 0) AS "uid_is_current_user"', $sql);
    $this->assertStringContainsString('ORDER BY "uid_is_current_user"', $sql);
  }

  /**
   * Test Views "greater_than" sort plugin.
   *
   * @covers \Drupal\improvements_views\Plugin\views\sort\GreaterThan
   */
  public function testViewsPluginSortGreaterThan(): void {
    $this->installModule('node', 'comment', 'user', 'improvements_views_test');

    // Check view exists
    $this->installModule('views_ui');
    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/views');
    $web_assert = $this->assertSession();
    $web_assert->pageTextContains('Test sort by comment author is registered');

    \Drupal::getContainer()->get('current_user')->setAccount($this->rootUser);
    $sql = (string)$this->getViewQuery('test_sort_by_comment_author_is_registered');
    $this->assertStringContainsString('IF(comment_field_data.uid > 0, 1, 0) AS "uid_greater_than"', $sql);
    $this->assertStringContainsString('ORDER BY "uid_greater_than"', $sql);
  }

  /**
   * Test token [view:total-rows-in-current-page].
   */
  public function testViewsTotalRowsToken(): void {
    $this->installModule('node', 'improvements_views_test');
    $this->createContentType(['type' => 'page', 'name' => 'Page']);
    $node1 = $this->createNode(['title' => 'Node 1 for test ' . __FUNCTION__]);
    $node2 = $this->createNode(['title' => 'Node 2 for test ' . __FUNCTION__]);
    $node3 = $this->createNode(['title' => 'Node 3 for test ' . __FUNCTION__]);
    $token_service = $this->container->get('token');
    $renderer = $this->container->get('renderer');

    $view_executable = $this->getExecutedView('test_total_rows_token');
    $total_rows = $token_service->replace('[view:total-rows-in-current-page]', ['view' => $view_executable]);
    $this->assertSame('3', $total_rows);

    $view_executable = $this->getExecutedView('test_total_rows_token', 'default', [], function (ViewExecutable $view) {
      $view->setItemsPerPage(2);
    });
    $total_rows = $token_service->replace('[view:total-rows-in-current-page]', ['view' => $view_executable]);
    $this->assertSame('2', $total_rows);

    $view_build = views_embed_view('test_total_rows_token');
    $view_output = (string)$renderer->renderRoot($view_build);
    $this->assertStringContainsString('<div class="content-css-class total-rows-3">', $view_output);
  }

  /**
   * Test prefix in Views display tab name.
   *
   * @covers ::improvements_views_ui_display_top_alter()
   */
  public function testViewsDisplayTabNamePrefix(): void {
    $this->installModule('improvements_views_test', 'views_ui');
    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/views/view/test_total_rows_token/edit/default');
    $this->dontSeeErrorMessage();
    $web_assert = $this->assertSession();
    $web_assert->elementTextContains('css', '#views-display-menu-tabs', '(default) Default');
  }

  /**
   * Test Views optional date exposed filter.
   */
  public function testViewsOptionalDateExposedFilter(): void {
    $this->installModule('improvements_views_test', 'node');
    $this->createContentType(['type' => 'page', 'name' => 'Page']);
    $nodes = [
      1 => $this->createNode(['created' => strtotime('2020-06-01')]),
      2 => $this->createNode(['created' => strtotime('2021-08-01')]),
    ];
    $web_assert = $this->assertSession();

    $this->drupalGet('/test-optional-date-exposed-filter');
    $web_assert->pageTextContains($nodes[1]->label());
    $web_assert->pageTextContains($nodes[2]->label());

    $this->submitForm([
      'created[min]' => '2020-01-01',
      'created[max]' => '2022-01-01',
    ], 'Apply');
    $web_assert->pageTextContains($nodes[1]->label());
    $web_assert->pageTextContains($nodes[2]->label());

    $this->submitForm([
      'created[min]' => '2021-01-01',
      'created[max]' => '2022-01-01',
    ], 'Apply');
    $web_assert->pageTextContains($nodes[2]->label());
    $web_assert->pageTextNotContains($nodes[1]->label());

    $this->submitForm([
      'created[min]' => '2020-01-01',
      'created[max]' => '',
    ], 'Apply');
    $web_assert->pageTextContains($nodes[1]->label());
    $web_assert->pageTextContains($nodes[2]->label());

    $this->submitForm([
      'created[min]' => '2021-01-01',
      'created[max]' => '',
    ], 'Apply');
    $web_assert->pageTextContains($nodes[2]->label());
    $web_assert->pageTextNotContains($nodes[1]->label());

    $this->submitForm([
      'created[min]' => '',
      'created[max]' => '2021-01-01',
    ], 'Apply');
    $web_assert->pageTextContains($nodes[1]->label());
    $web_assert->pageTextNotContains($nodes[2]->label());
  }

  /**
   * Test Views argument plugin "term_with_children".
   *
   * @covers \Drupal\improvements_views\Plugin\views\argument\TermWithChildrenArgument
   */
  public function testViewsPluginArgumentTermWithChildren(): void {
    $this->installModule('node', 'taxonomy', 'improvements_views_test', 'views_ui');
    $this->createContentType(['type' => 'page', 'name' => 'Page']);
    $categories_vocabulary = Vocabulary::create(['name' => 'Categories', 'vid' => 'category']);
    $this->createField(
      entity_type: 'node',
      entity_bundle: 'page',
      field_name: 'field_category',
      field_type: 'entity_reference',
      field_label: 'Test category field',
      storage_settings: [
        'settings' => [
          'target_type' => 'taxonomy_term',
        ],
      ],
    );

    $this->drupalLoginAsRoot();
    $this->drupalGet('/admin/structure/views/nojs/add-handler/test_argument_term_with_children/default/argument');
    $this->dontSeeErrorMessage();
    $web_assert = $this->assertSession();
    $web_assert->fieldExists('name[node__field_category.field_category_target_id_with_children]');

    $this->submitForm([
      'name[node__field_category.field_category_target_id_with_children]' => 'node__field_category.field_category_target_id_with_children',
    ], 'Add and configure contextual filters');
    $this->dontSeeErrorMessage();
    $this->drupalGet('/admin/structure/views/view/test_argument_term_with_children');
    $this->dontSeeErrorMessage();
    $this->submitForm([], 'Save');
    $this->dontSeeErrorMessage();

    $term_1 = $this->createTerm($categories_vocabulary, ['name' => 'Term 1']);
    $term_2 = $this->createTerm($categories_vocabulary, ['name' => 'Term 2']);
    $term_1_1 = $this->createTerm($categories_vocabulary, ['name' => 'Term 1.1', 'parent' => [$term_1->id()]]);
    $term_1_2 = $this->createTerm($categories_vocabulary, ['name' => 'Term 1.2', 'parent' => [$term_1->id()]]);

    $query = $this->getViewQuery('test_argument_term_with_children', 'default', [$term_1->id()]);
    $this->assertSame([
      (string)$term_1->id(),
      (string)$term_1_1->id(),
      (string)$term_1_2->id(),
    ], current($query->getArguments()));

    $query = $this->getViewQuery('test_argument_term_with_children', 'default', [$term_2->id()]);
    $this->assertSame((string)$term_2->id(), current($query->getArguments()));
  }

  /**
   * Test bulk edit terms Views.
   *
   * @TODO Move to improvements_taxonomy module?
   */
  public function testTermBulkEditViews(): void {
    $this->installModule('views', 'block', 'taxonomy', 'user', 'improvements_taxonomy');
    $this->placeBlock('local_tasks_block', [
      'id' => 'local_tasks_block',
      'region' => 'help',
      'weight' => 3,
    ]);

    ($categories_vocabulary = Vocabulary::create(['name' => 'Categories', 'vid' => 'category']))->save();
    ($tags_vocabulary = Vocabulary::create(['name' => 'Tags', 'vid' => 'tag']))->save();

    $term1 = $this->createTerm($categories_vocabulary, ['name' => 'Test category for ' . __FUNCTION__]);
    $term2 = $this->createTerm($tags_vocabulary, ['name' => 'Test tag for ' . __FUNCTION__]);

    $this->drupalLoginAsRoot();
    $web_assert = $this->assertSession();

    $this->installModule('views_ui');
    $this->drupalGet('/admin/structure/views');
    $web_assert->pageTextContains('Administer terms');

    $this->drupalGet("/admin/structure/taxonomy/manage/{$categories_vocabulary->id()}/overview");
    $this->dontSeeErrorMessage();
    $web_assert->elementExists('css', '#block-local-tasks-block');
    $web_assert->elementExists('css', '#block-local-tasks-block a[href="/admin/structure/taxonomy/manage/' . $categories_vocabulary->id() . '/bulk-edit"]');

    $this->drupalGet("/admin/structure/taxonomy/manage/{$tags_vocabulary->id()}/overview");
    $this->dontSeeErrorMessage();
    $web_assert->elementExists('css', '#block-local-tasks-block a[href="/admin/structure/taxonomy/manage/' . $tags_vocabulary->id() . '/bulk-edit"]');

    $this->drupalGet("/admin/structure/taxonomy/manage/{$categories_vocabulary->id()}/bulk-edit");
    $this->dontSeeErrorMessage();
    $web_assert->elementExists('css', "form#views-form-admin-terms-page-{$categories_vocabulary->id()}");
    $web_assert->pageTextContains($term1->label());
    $web_assert->pageTextNotContains($term2->label());

    $this->drupalGet("/admin/structure/taxonomy/manage/{$tags_vocabulary->id()}/bulk-edit");
    $this->dontSeeErrorMessage();
    $web_assert->elementExists('css', "form#views-form-admin-terms-page-{$tags_vocabulary->id()}");
    $web_assert->pageTextContains($term2->label());
    $web_assert->pageTextNotContains($term1->label());
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc