You are here

class ListWidgetTest in Select (or other) 8

Same name and namespace in other branches
  1. 4.x tests/src/Unit/ListWidgetTest.php \Drupal\Tests\select_or_other\Unit\ListWidgetTest

Tests the form element implementation.

@group select_or_other

@covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget

Hierarchy

Expanded class hierarchy of ListWidgetTest

File

tests/src/Unit/ListWidgetTest.php, line 18

Namespace

Drupal\Tests\select_or_other\Unit
View source
class ListWidgetTest extends UnitTestBase {

  /**
   * @return string
   *   The fully qualified class name of the subject under test.
   */
  protected function getTestedClassName() {
    return 'Drupal\\select_or_other\\Plugin\\Field\\FieldWidget\\ListWidget';
  }

  /**
   * Test if defaultSettings() returns the correct keys.
   */
  public function testGetOptions() {
    $expected = [
      1,
      2,
    ];
    $options_provider = $this
      ->getMockForAbstractClass('Drupal\\Core\\TypedData\\OptionsProviderInterface');
    $options_provider
      ->method('getSettableOptions')
      ->willReturn($expected);
    $storage_definition = $this
      ->getMockForAbstractClass('Drupal\\Core\\Field\\FieldStorageDefinitionInterface');
    $storage_definition
      ->method('getOptionsProvider')
      ->willReturn($options_provider);
    $field_definition = $this
      ->getMockForAbstractClass('Drupal\\Core\\Field\\FieldDefinitionInterface');
    $field_definition
      ->method('getFieldStorageDefinition')
      ->willReturn($storage_definition);
    $constructor_arguments = [
      '',
      '',
      $field_definition,
      [],
      [],
    ];
    $mock = $this->mockBuilder
      ->setConstructorArgs($constructor_arguments)
      ->setMethods([
      'getColumn',
    ])
      ->getMock();
    $mock
      ->method('getColumn')
      ->willReturn([
      'column',
    ]);
    $get_options = new ReflectionMethod($mock, 'getOptions');
    $get_options
      ->setAccessible(TRUE);
    $options = $get_options
      ->invoke($mock, $this
      ->getMockForAbstractClass('Drupal\\Core\\Entity\\FieldableEntityInterface'));
    $this
      ->assertArrayEquals($expected, $options);
  }

  /**
   * Test if formElement() adds the expected information.
   */
  public function testFormElement() {
    list($parent, $mock) = $this
      ->getBasicMocks();

    /** @var ListWidget $mock */

    /** @var WidgetBase $parent */

    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    $items = $this
      ->getMockForAbstractClass('Drupal\\Core\\Field\\FieldItemListInterface');
    $delta = NULL;
    $element = [];
    $form = [];
    $form_state = new FormState();
    $parent_result = $parent
      ->formElement($items, $delta, $element, $form, $form_state);
    $result = $mock
      ->formElement($items, $delta, $element, $form, $form_state);
    $added = array_diff_key($result, $parent_result);
    $expected = [
      '#merged_values' => TRUE,
      '#original_options' => [],
      '#other_options' => [],
    ];
    $this
      ->assertArrayEquals($expected, $added);
  }

  /**
   * @test
   */
  public function massageFormValuesReturnsValuesPassedToIt() {
    $sut = $this
      ->getNewSubjectUnderTest();
    $form = [];
    $form_state = new FormState();

    /** @var ListWidget $mock */
    $test_values = [
      [],
      [
        'value',
      ],
      [
        'multiple',
        'values',
      ],
    ];
    foreach ($test_values as $values) {
      $result = $sut
        ->massageFormValues($values, $form, $form_state);
      $this
        ->assertArrayEquals($values, $result);
    }
  }

  /**
   * @test
   */
  public function massageFormValuesRemovesSelectValueIfPresent() {
    $sut = $this
      ->getNewSubjectUnderTest();
    $form = [];
    $form_state = new FormState();

    /** @var ListWidget $mock */
    $result = $sut
      ->massageFormValues([
      'select' => 'test',
    ], $form, $form_state);
    $this
      ->assertArrayEquals([], $result);
  }

  /**
   * @test
   */
  public function massageFormValuesRemovesOtherValueIfPresent() {
    $sut = $this
      ->getNewSubjectUnderTest();
    $form = [];
    $form_state = new FormState();

    /** @var ListWidget $mock */
    $result = $sut
      ->massageFormValues([
      'other' => 'test',
    ], $form, $form_state);
    $this
      ->assertArrayEquals([], $result);
  }

  /**
   * @test
   * @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::extractNewValues
   * @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::AddNewValuesToAllowedValues
   */
  public function massageFormValuesAddsNewValuesToAllowedValues() {
    $allowed_values = [
      't' => 'test',
    ];
    $field_definition = $this
      ->getMockForAbstractClass('\\Drupal\\Core\\Field\\FieldDefinitionInterface');
    $field_definition
      ->method('getSetting')
      ->willReturn($allowed_values);
    $sut = $this
      ->getNewSubjectUnderTest($field_definition);
    $field_storage_config = $this
      ->getMockForAbstractClass('\\Drupal\\field\\FieldStorageConfigInterface');
    $field_storage_config
      ->expects($this
      ->once())
      ->method('setSetting')
      ->willReturnSelf();
    $field_storage_config
      ->expects($this
      ->once())
      ->method('save');
    $entity_storage_methods = [
      'load' => $field_storage_config,
    ];
    $entity_type_manager_methods = [
      'getStorage' => $this
        ->getMockForAbstractClassWithMethods('\\Drupal\\Core\\Entity\\EntityStorageInterface', $entity_storage_methods),
    ];
    $entity_type_manager_mock = $this
      ->getMockForAbstractClassWithMethods('\\Drupal\\Core\\Entity\\EntityTypeManagerInterface', $entity_type_manager_methods);
    $this
      ->registerServiceWithContainerMock('entity_type.manager', $entity_type_manager_mock);
    $form = [];
    $form_state = new FormState();

    // First invocation does not call setSetting or save.
    $sut
      ->massageFormValues([
      't',
    ], $form, $form_state);

    // Second invocation calls setSetting and save.
    $sut
      ->massageFormValues([
      't',
      'est',
    ], $form, $form_state);
  }

  /**
   * @test
   * @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::extractNewValues
   * @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::AddNewValuesToAllowedValues
   */
  public function massageFormValuesDoNotAddOtherValuesToAllowedValues() {
    $allowed_values = [
      't' => 'test',
    ];
    $field_definition = $this
      ->getMockForAbstractClass('\\Drupal\\Core\\Field\\FieldDefinitionInterface');
    $field_definition
      ->method('getSetting')
      ->willReturn($allowed_values);
    $sut = $this
      ->getNewSubjectUnderTest($field_definition);
    $field_storage_config = $this
      ->getMockForAbstractClass('\\Drupal\\field\\FieldStorageConfigInterface');
    $field_storage_config
      ->expects($this
      ->never())
      ->method('setSetting')
      ->willReturnSelf();
    $field_storage_config
      ->expects($this
      ->never())
      ->method('save');
    $entity_storage_methods = [
      'load' => $field_storage_config,
    ];
    $entity_type_manager_methods = [
      'getStorage' => $this
        ->getMockForAbstractClassWithMethods('\\Drupal\\Core\\Entity\\EntityStorageInterface', $entity_storage_methods),
    ];
    $entity_type_manager_mock = $this
      ->getMockForAbstractClassWithMethods('\\Drupal\\Core\\Entity\\EntityTypeManagerInterface', $entity_type_manager_methods);
    $this
      ->registerServiceWithContainerMock('entity_type.manager', $entity_type_manager_mock);
    $form = [];
    $form_state = new FormState();
    $sut
      ->setSetting('add_other_value_to_allowed_values', FALSE);

    // First invocation does not call setSetting or save.
    $sut
      ->massageFormValues([
      't',
    ], $form, $form_state);

    // Second invocation calls setSetting and save.
    $sut
      ->massageFormValues([
      't',
      'est',
    ], $form, $form_state);
  }
  protected function getNewSubjectUnderTest(FieldDefinitionInterface $fieldDefinition = NULL) {
    $widget_id = 'widget_id';
    $plugin_definition = 'plugin_definition';
    if (empty($fieldDefinition)) {
      $fieldDefinition = $this
        ->getMockForAbstractClass('\\Drupal\\Core\\Field\\FieldDefinitionInterface');
    }
    $settings = [];
    $third_party_settings = [];
    return new ListWidget($widget_id, $plugin_definition, $fieldDefinition, $settings, $third_party_settings);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ListWidgetTest::getNewSubjectUnderTest protected function
ListWidgetTest::getTestedClassName protected function Overrides UnitTestBase::getTestedClassName
ListWidgetTest::massageFormValuesAddsNewValuesToAllowedValues public function @test @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::extractNewValues @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::AddNewValuesToAllowedValues
ListWidgetTest::massageFormValuesDoNotAddOtherValuesToAllowedValues public function @test @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::extractNewValues @covers Drupal\select_or_other\Plugin\Field\FieldWidget\ListWidget::AddNewValuesToAllowedValues
ListWidgetTest::massageFormValuesRemovesOtherValueIfPresent public function @test
ListWidgetTest::massageFormValuesRemovesSelectValueIfPresent public function @test
ListWidgetTest::massageFormValuesReturnsValuesPassedToIt public function @test
ListWidgetTest::testFormElement public function Test if formElement() adds the expected information.
ListWidgetTest::testGetOptions public function Test if defaultSettings() returns the correct keys.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestBase::$containerMock private property
UnitTestBase::$mockBuilder protected property
UnitTestBase::$services private property @var array $services
UnitTestBase::addMockServicesToContainer private function Adds mocked services to the container.
UnitTestBase::containerMockGetServiceCallback public function Callback for the get method on the mocked service container.
UnitTestBase::getBasicMocks protected function Creates and returns two basic mocks.
UnitTestBase::getMockForAbstractClassWithMethods protected function Creates a mock for an abstract class with some mapped methods.
UnitTestBase::getNewEntityTypeManagerMock private function
UnitTestBase::getNewUserMock private function Creates and returns a mocked user.
UnitTestBase::prepareContainer private function Prepares a mocked service container.
UnitTestBase::registerServiceWithContainerMock protected function Registers a (mocked) service with the mocked service container.
UnitTestBase::setUp protected function Overrides UnitTestCase::setUp
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.