You are here

EntityFieldExportTest.php in REST Views 8

Same filename and directory in other branches
  1. 2.0.x tests/src/Unit/EntityFieldExportTest.php

File

tests/src/Unit/EntityFieldExportTest.php
View source
<?php

namespace Drupal\Tests\rest_views\Unit;

use Drupal;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldTypePluginManagerInterface;
use Drupal\Core\Field\FormatterPluginManager;
use Drupal\Core\Form\FormState;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\rest_views\Normalizer\DataNormalizer;
use Drupal\rest_views\Normalizer\RenderNormalizer;
use Drupal\rest_views\Plugin\views\field\EntityFieldExport;
use Drupal\rest_views\SerializedData;
use Drupal\serialization\Encoder\JsonEncoder;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
use Symfony\Component\Serializer\Serializer;

/**
 * Test the EntityFieldExport views field plugin.
 *
 * @group rest_views
 */
class EntityFieldExportTest extends UnitTestCase {

  /**
   * The EntityFieldExport plugin.
   *
   * @var \Drupal\rest_views\Plugin\views\field\EntityFieldExport|\PHPUnit_Framework_MockObject_MockObject
   */
  private $handler;

  /**
   * The mocked serializer service.
   *
   * @var \Symfony\Component\Serializer\SerializerInterface
   */
  private $serializer;

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

    // Create our field handler, mocking the required services.
    $entityManager = $this
      ->getMock(EntityManagerInterface::class);
    $formatterPluginManager = $this
      ->getMockBuilder(FormatterPluginManager::class)
      ->disableOriginalConstructor()
      ->getMock();
    $fieldTypePluginManager = $this
      ->getMock(FieldTypePluginManagerInterface::class);
    $languageManager = $this
      ->getMock(LanguageManagerInterface::class);

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this
      ->getMock(RendererInterface::class);

    // For the t() function to work, mock the translation service.
    $container = new ContainerBuilder();
    $translation = $this
      ->getMock(TranslationInterface::class);
    $translation
      ->method('translateString')
      ->willReturnCallback(static function (TranslatableMarkup $string) {
      return $string
        ->getUntranslatedString();
    });
    $container
      ->set('string_translation', $translation);
    $container
      ->set('entity.repository', $entityManager);
    $container
      ->set('entity_field.manager', $entityManager);
    Drupal::setContainer($container);
    $this->handler = $this
      ->getMockBuilder(EntityFieldExport::class)
      ->setConstructorArgs([
      [],
      NULL,
      [
        'entity_type' => 'node',
        'field_name' => 'title',
      ],
      $entityManager,
      $formatterPluginManager,
      $fieldTypePluginManager,
      $languageManager,
      $renderer,
    ])
      ->setMethods([
      'getFieldDefinition',
    ])
      ->getMock();

    // Mock the field definition.
    $fieldDefinition = $this
      ->getMock(BaseFieldDefinition::class);
    $fieldDefinition
      ->method('getFieldStorageDefinition')
      ->willReturn($fieldDefinition);
    $fieldDefinition
      ->method('getColumns')
      ->willReturn([]);

    // The handler accesses it through itself, and through the entity manager.
    $this->handler
      ->method('getFieldDefinition')
      ->willReturn($fieldDefinition);
    $entityManager
      ->method('getFieldStorageDefinitions')
      ->with('node')
      ->willReturn([
      'title' => $fieldDefinition,
    ]);

    // Initialize the handler, using a mocked view and display plugin.

    /** @var \Drupal\views\ViewExecutable $view */
    $view = $this
      ->getMockBuilder(ViewExecutable::class)
      ->disableOriginalConstructor()
      ->getMock();
    $view->display_handler = $this
      ->getMockBuilder(DisplayPluginBase::class)
      ->disableOriginalConstructor()
      ->getMock();
    $this->handler
      ->init($view, $view->display_handler);
    $this->serializer = new Serializer([
      new DataNormalizer(),
      new RenderNormalizer($renderer),
    ], [
      new JsonEncoder(),
    ]);
  }

  /**
   * Check that the field does not use multi-type and separator options.
   */
  public function testSettings() {
    $options = $this->handler
      ->defineOptions();
    $this
      ->assertArrayNotHasKey('multi_type', $options);
    $this
      ->assertArrayNotHasKey('separator', $options);
    $form = [];
    $this->handler
      ->multiple_options_form($form, new FormState());
    $this
      ->assertArrayNotHasKey('multi_type', $form);
    $this
      ->assertArrayNotHasKey('separator', $form);
  }

  /**
   * Check that the handler correctly preserves serializable items.
   *
   * @param array $items
   *   Item data to be rendered.
   * @param array $expected
   *   Expected output.
   *
   * @dataProvider providerItems
   *
   * @throws \Exception
   */
  public function testRenderItems(array $items, array $expected) {
    $this->handler->multiple = FALSE;
    $result = $this->handler
      ->renderItems($items);
    $json = $this->serializer
      ->serialize($result, 'json');
    $expected_json = $this->serializer
      ->serialize($expected[0], 'json');
    $this
      ->assertEquals($expected_json, $json);
    $this->handler->multiple = TRUE;
    $result = $this->handler
      ->renderItems($items);
    $json = $this->serializer
      ->serialize($result, 'json');
    $expected_json = $this->serializer
      ->serialize($expected, 'json');
    $this
      ->assertEquals($expected_json, $json);
  }

  /**
   * Data provider for ::testRenderItems().
   *
   * @return array
   *   Test case data.
   */
  public function providerItems() {
    $data[] = [
      'items' => [
        'Lorem',
        'ipsum',
        'dolor',
        'sit',
        'amet',
      ],
      'expected' => [
        'Lorem',
        'ipsum',
        'dolor',
        'sit',
        'amet',
      ],
    ];
    $data[] = [
      'items' => [
        new SerializedData([
          'lorem' => 'ipsum',
        ]),
        new SerializedData([
          'dolor' => TRUE,
        ]),
        new SerializedData([
          'amet' => 42,
        ]),
      ],
      'expected' => [
        [
          'lorem' => 'ipsum',
        ],
        [
          'dolor' => TRUE,
        ],
        [
          'amet' => 42,
        ],
      ],
    ];
    return $data;
  }

}

Classes

Namesort descending Description
EntityFieldExportTest Test the EntityFieldExport views field plugin.