You are here

public function DenormalizeTest::testMarkFieldForDeletion in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/hal/tests/src/Kernel/DenormalizeTest.php \Drupal\Tests\hal\Kernel\DenormalizeTest::testMarkFieldForDeletion()

Tests that a field set to an empty array is different than an absent field.

File

core/modules/hal/tests/src/Kernel/DenormalizeTest.php, line 110

Class

DenormalizeTest
Tests HAL denormalization edge cases for EntityResource.

Namespace

Drupal\Tests\hal\Kernel

Code

public function testMarkFieldForDeletion() {

  // Add a default value for a field.
  $field = FieldConfig::loadByName('entity_test', 'entity_test', 'field_test_text');
  $field
    ->setDefaultValue([
    [
      'value' => 'Llama',
    ],
  ]);
  $field
    ->save();

  // Denormalize data that contains no entry for the field, and check that
  // the default value is present in the resulting entity.
  $data = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
          'absolute' => TRUE,
        ])
          ->toString(),
      ],
    ],
  ];
  $entity = $this->serializer
    ->denormalize($data, $this->entityClass, $this->format);
  $this
    ->assertEquals(1, $entity->field_test_text
    ->count());
  $this
    ->assertEquals('Llama', $entity->field_test_text->value);

  // Denormalize data that contains an empty entry for the field, and check
  // that the field is empty in the resulting entity.
  $data = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
          'absolute' => TRUE,
        ])
          ->toString(),
      ],
    ],
    'field_test_text' => [],
  ];
  $entity = $this->serializer
    ->denormalize($data, get_class($entity), $this->format, [
    'target_instance' => $entity,
  ]);
  $this
    ->assertEquals(0, $entity->field_test_text
    ->count());
}