You are here

public function DenormalizeTest::testTypeHandling in Drupal 8

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

Tests that the type link relation in incoming data is handled correctly.

File

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

Class

DenormalizeTest
Tests HAL denormalization edge cases for EntityResource.

Namespace

Drupal\Tests\hal\Kernel

Code

public function testTypeHandling() {

  // Valid type.
  $data_with_valid_type = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
          'absolute' => TRUE,
        ])
          ->toString(),
      ],
    ],
  ];
  $denormalized = $this->serializer
    ->denormalize($data_with_valid_type, $this->entityClass, $this->format);
  $this
    ->assertEqual(get_class($denormalized), $this->entityClass, 'Request with valid type results in creation of correct bundle.');

  // Multiple types.
  $data_with_multiple_types = [
    '_links' => [
      'type' => [
        [
          'href' => Url::fromUri('base:rest/types/foo', [
            'absolute' => TRUE,
          ])
            ->toString(),
        ],
        [
          'href' => Url::fromUri('base:rest/type/entity_test/entity_test', [
            'absolute' => TRUE,
          ])
            ->toString(),
        ],
      ],
    ],
  ];
  $denormalized = $this->serializer
    ->denormalize($data_with_multiple_types, $this->entityClass, $this->format);
  $this
    ->assertEqual(get_class($denormalized), $this->entityClass, 'Request with multiple types results in creation of correct bundle.');

  // Invalid type.
  $data_with_invalid_type = [
    '_links' => [
      'type' => [
        'href' => Url::fromUri('base:rest/types/foo', [
          'absolute' => TRUE,
        ])
          ->toString(),
      ],
    ],
  ];
  try {
    $this->serializer
      ->denormalize($data_with_invalid_type, $this->entityClass, $this->format);
    $this
      ->fail('Exception should be thrown when type is invalid.');
  } catch (UnexpectedValueException $e) {

    // Expected exception; just continue testing.
  }

  // No type.
  $data_with_no_type = [
    '_links' => [],
  ];
  try {
    $this->serializer
      ->denormalize($data_with_no_type, $this->entityClass, $this->format);
    $this
      ->fail('Exception should be thrown when no type is provided.');
  } catch (UnexpectedValueException $e) {

    // Expected exception; just continue testing.
  }
}