class JsonApiTopLevelResourceNormalizerTest

Same name and namespace in other branches
  1. main core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiTopLevelResourceNormalizerTest.php \Drupal\Tests\jsonapi\Kernel\Normalizer\JsonApiTopLevelResourceNormalizerTest

Tests Drupal\jsonapi\Normalizer\JsonApiDocumentTopLevelNormalizer.

@internal

Attributes

#[CoversClass(JsonApiDocumentTopLevelNormalizer::class)] #[Group('jsonapi')] #[RunTestsInSeparateProcesses]

Hierarchy

Expanded class hierarchy of JsonApiTopLevelResourceNormalizerTest

File

core/modules/jsonapi/tests/src/Kernel/Normalizer/JsonApiTopLevelResourceNormalizerTest.php, line 45

Namespace

Drupal\Tests\jsonapi\Kernel\Normalizer
View source
class JsonApiTopLevelResourceNormalizerTest extends JsonapiKernelTestBase {
  use ImageFieldCreationTrait;
  use JsonApiJsonSchemaTestTrait;
  
  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'field',
    'node',
    'serialization',
    'system',
    'taxonomy',
    'text',
    'filter',
    'user',
    'image',
    'jsonapi_test_normalizers_kernel',
    'jsonapi_test_resource_type_building',
  ];
  
  /**
   * A node to normalize.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $node;
  
  /**
   * The node type.
   *
   * @var \Drupal\node\Entity\NodeType
   */
  protected NodeType $nodeType;
  
  /**
   * A user to normalize.
   *
   * @var \Drupal\user\Entity\User
   */
  protected $user;
  
  /**
   * A user.
   *
   * @var \Drupal\user\Entity\User
   */
  protected User $user2;
  
  /**
   * A vocabulary.
   *
   * @var \Drupal\taxonomy\Entity\Vocabulary
   */
  protected Vocabulary $vocabulary;
  
  /**
   * A term.
   *
   * @var \Drupal\taxonomy\Entity\Term
   */
  protected Term $term1;
  
  /**
   * A term.
   *
   * @var \Drupal\taxonomy\Entity\Term
   */
  protected Term $term2;
  
  /**
   * The include resolver.
   *
   * @var \Drupal\jsonapi\IncludeResolver
   */
  protected $includeResolver;
  
  /**
   * The JSON:API resource type repository under test.
   *
   * @var \Drupal\jsonapi\ResourceType\ResourceTypeRepository
   */
  protected $resourceTypeRepository;
  
  /**
   * @var \Drupal\file\Entity\File
   */
  private $file;
  
  /**
   * {@inheritdoc}
   */
  protected function setUp() : void {
    parent::setUp();
    // Add the entity schemas.
    $this->installEntitySchema('node');
    $this->installEntitySchema('user');
    $this->installEntitySchema('taxonomy_term');
    $this->installEntitySchema('file');
    // Add the additional table schemas.
    $this->installSchema('node', [
      'node_access',
    ]);
    $this->installSchema('user', [
      'users_data',
    ]);
    $this->installSchema('file', [
      'file_usage',
    ]);
    $type = NodeType::create([
      'type' => 'article',
      'name' => 'Article',
    ]);
    $type->save();
    $this->createEntityReferenceField('node', 'article', 'field_tags', 'Tags', 'taxonomy_term', 'default', [
      'target_bundles' => [
        'tags',
      ],
    ], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
    $this->createTextField('node', 'article', 'body', 'Body');
    $this->createImageField('field_image', 'node', 'article');
    $this->user = User::create([
      'name' => 'user1',
      'mail' => 'user@localhost',
    ]);
    $this->user2 = User::create([
      'name' => 'user2',
      'mail' => 'user2@localhost',
    ]);
    $this->user
      ->save();
    $this->user2
      ->save();
    $this->vocabulary = Vocabulary::create([
      'name' => 'Tags',
      'vid' => 'tags',
    ]);
    $this->vocabulary
      ->save();
    $this->term1 = Term::create([
      'name' => 'term1',
      'vid' => $this->vocabulary
        ->id(),
    ]);
    $this->term2 = Term::create([
      'name' => 'term2',
      'vid' => $this->vocabulary
        ->id(),
    ]);
    $this->term1
      ->save();
    $this->term2
      ->save();
    $this->file = File::create([
      'uri' => 'public://example.png',
      'filename' => 'example.png',
    ]);
    $this->file
      ->save();
    $this->node = Node::create([
      'title' => 'dummy_title',
      'type' => 'article',
      'uid' => $this->user,
      'body' => [
        'format' => 'plain_text',
        'value' => $this->randomString(),
      ],
      'field_tags' => [
        [
          'target_id' => $this->term1
            ->id(),
        ],
        [
          'target_id' => $this->term2
            ->id(),
        ],
      ],
      'field_image' => [
        [
          'target_id' => $this->file
            ->id(),
          'alt' => 'test alt',
          'title' => 'test title',
          'width' => 10,
          'height' => 11,
        ],
      ],
    ]);
    $this->node
      ->save();
    $this->nodeType = NodeType::load('article');
    Role::create([
      'id' => RoleInterface::ANONYMOUS_ID,
      'permissions' => [
        'access content',
      ],
      'label' => 'Anonymous',
    ])->save();
    $this->includeResolver = $this->container
      ->get('jsonapi.include_resolver');
    $this->resourceTypeRepository = $this->container
      ->get('jsonapi.resource_type.repository');
  }
  
  /**
   * {@inheritdoc}
   */
  protected function tearDown() : void {
    if ($this->node) {
      $this->node
        ->delete();
    }
    if ($this->term1) {
      $this->term1
        ->delete();
    }
    if ($this->term2) {
      $this->term2
        ->delete();
    }
    if ($this->vocabulary) {
      $this->vocabulary
        ->delete();
    }
    if ($this->user) {
      $this->user
        ->delete();
    }
    if ($this->user2) {
      $this->user2
        ->delete();
    }
    parent::tearDown();
  }
  
  /**
   * Get a test resource type, resource object and includes.
   *
   * @return array
   *   Indexed array with values:
   *     - Resource type.
   *     - Resource object.
   *     - Includes.
   */
  protected function getTestContentEntityResource() : array {
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $includes = $this->includeResolver
      ->resolve($resource_object, 'uid,field_tags,field_image');
    return [
      $resource_type,
      $resource_object,
      $includes,
    ];
  }
  
  /**
   * Get a test resource type, resource object and includes for config entity.
   *
   * @return array
   *   Indexed array with values:
   *     - Resource type.
   *     - Resource object.
   *     - Includes.
   */
  protected function getTestConfigEntityResource() : array {
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('action', 'action');
    $resource_object = ResourceObject::createFromEntity($resource_type, Action::create([
      'id' => 'user_add_role_action.' . RoleInterface::ANONYMOUS_ID,
      'type' => 'user',
      'label' => 'Add the anonymous role to the selected users',
      'configuration' => [
        'rid' => RoleInterface::ANONYMOUS_ID,
      ],
      'plugin' => 'user_add_role_action',
    ]));
    return [
      $resource_type,
      $resource_object,
      new NullIncludedData(),
    ];
  }
  
  /**
   * Tests normalize.
   */
  public function testNormalize() : void {
    [$resource_type, $resource_object, $includes] = $this->getTestContentEntityResource();
    $jsonapi_doc_object = $this->getNormalizer()
      ->normalize(new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
    ], 1), $includes, new LinkCollection([])), 'api_json', [
      'resource_type' => $resource_type,
      'account' => NULL,
      'sparse_fieldset' => [
        'node--article' => [
          'title',
          'node_type',
          'uid',
          'field_tags',
          'field_image',
        ],
        'user--user' => [
          'display_name',
        ],
      ],
      'include' => [
        'uid',
        'field_tags',
        'field_image',
      ],
    ]);
    $normalized = $jsonapi_doc_object->getNormalization();
    // @see https://jsonapi.org/format/#document-jsonapi-object
    $this->assertEquals(JsonApiSpec::SUPPORTED_SPECIFICATION_VERSION, $normalized['jsonapi']['version']);
    $this->assertEquals(JsonApiSpec::SUPPORTED_SPECIFICATION_PERMALINK, $normalized['jsonapi']['meta']['links']['self']['href']);
    $this->assertSame($normalized['data']['attributes']['title'], 'dummy_title');
    $this->assertEquals($normalized['data']['id'], $this->node
      ->uuid());
    $this->assertSame([
      'data' => [
        'type' => 'node_type--node_type',
        'id' => NodeType::load('article')->uuid(),
        'meta' => [
          'drupal_internal__target_id' => 'article',
        ],
      ],
      'links' => [
        'related' => [
          'href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node
            ->uuid() . '/node_type', [
            'query' => [
              'resourceVersion' => 'id:' . $this->node
                ->getRevisionId(),
            ],
          ])
            ->setAbsolute()
            ->toString(TRUE)
            ->getGeneratedUrl(),
        ],
        'self' => [
          'href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node
            ->uuid() . '/relationships/node_type', [
            'query' => [
              'resourceVersion' => 'id:' . $this->node
                ->getRevisionId(),
            ],
          ])
            ->setAbsolute()
            ->toString(TRUE)
            ->getGeneratedUrl(),
        ],
      ],
    ], $normalized['data']['relationships']['node_type']);
    $this->assertTrue(!isset($normalized['data']['attributes']['created']));
    $this->assertEquals([
      'alt' => 'test alt',
      'title' => 'test title',
      'width' => 10,
      'height' => 11,
      'drupal_internal__target_id' => $this->file
        ->id(),
    ], $normalized['data']['relationships']['field_image']['data']['meta']);
    $this->assertSame('node--article', $normalized['data']['type']);
    $this->assertEquals([
      'data' => [
        'type' => 'user--user',
        'id' => $this->user
          ->uuid(),
        'meta' => [
          'drupal_internal__target_id' => $this->user
            ->id(),
        ],
      ],
      'links' => [
        'self' => [
          'href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node
            ->uuid() . '/relationships/uid', [
            'query' => [
              'resourceVersion' => 'id:' . $this->node
                ->getRevisionId(),
            ],
          ])
            ->setAbsolute()
            ->toString(TRUE)
            ->getGeneratedUrl(),
        ],
        'related' => [
          'href' => Url::fromUri('internal:/jsonapi/node/article/' . $this->node
            ->uuid() . '/uid', [
            'query' => [
              'resourceVersion' => 'id:' . $this->node
                ->getRevisionId(),
            ],
          ])
            ->setAbsolute()
            ->toString(TRUE)
            ->getGeneratedUrl(),
        ],
      ],
    ], $normalized['data']['relationships']['uid']);
    $this->assertArrayNotHasKey('meta', $normalized);
    $this->assertSame($this->user
      ->uuid(), $normalized['included'][0]['id']);
    $this->assertSame('user--user', $normalized['included'][0]['type']);
    $this->assertSame('user1', $normalized['included'][0]['attributes']['display_name']);
    $this->assertCount(1, $normalized['included'][0]['attributes']);
    $this->assertSame($this->term1
      ->uuid(), $normalized['included'][1]['id']);
    $this->assertSame('taxonomy_term--tags', $normalized['included'][1]['type']);
    $this->assertSame($this->term1
      ->label(), $normalized['included'][1]['attributes']['name']);
    $this->assertCount(11, $normalized['included'][1]['attributes']);
    $this->assertTrue(!isset($normalized['included'][1]['attributes']['created']));
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
    $this->assertEqualsCanonicalizing([
      'file:1',
      'node:1',
      'taxonomy_term:1',
      'taxonomy_term:2',
      'user:1',
    ], $jsonapi_doc_object->getCacheTags());
    $this->assertSame(Cache::PERMANENT, $jsonapi_doc_object->getCacheMaxAge());
  }
  
  /**
   * Tests normalize uuid.
   */
  public function testNormalizeUuid() : void {
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $include_param = 'uid,field_tags';
    $includes = $this->includeResolver
      ->resolve($resource_object, $include_param);
    $document_wrapper = new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
    ], 1), $includes, new LinkCollection([]));
    $jsonapi_doc_object = $this->getNormalizer()
      ->normalize($document_wrapper, 'api_json', [
      'resource_type' => $resource_type,
      'account' => NULL,
      'include' => [
        'uid',
        'field_tags',
      ],
    ]);
    $normalized = $jsonapi_doc_object->getNormalization();
    $this->assertStringMatchesFormat($this->node
      ->uuid(), $normalized['data']['id']);
    $this->assertEquals($this->node->type->entity
      ->uuid(), $normalized['data']['relationships']['node_type']['data']['id']);
    $this->assertEquals($this->user
      ->uuid(), $normalized['data']['relationships']['uid']['data']['id']);
    $this->assertNotEmpty($normalized['included'][0]['id']);
    $this->assertArrayNotHasKey('meta', $normalized);
    $this->assertEquals($this->user
      ->uuid(), $normalized['included'][0]['id']);
    $this->assertCount(1, $normalized['included'][0]['attributes']);
    $this->assertCount(11, $normalized['included'][1]['attributes']);
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
    $this->assertEqualsCanonicalizing([
      'node:1',
      'taxonomy_term:1',
      'taxonomy_term:2',
      'user:1',
    ], $jsonapi_doc_object->getCacheTags());
  }
  
  /**
   * Tests normalize exception.
   */
  public function testNormalizeException() : void {
    $normalized = $this->container
      ->get('jsonapi.serializer')
      ->normalize(new JsonApiDocumentTopLevel(new ErrorCollection([
      new BadRequestHttpException('Lorem'),
    ]), new NullIncludedData(), new LinkCollection([])), 'api_json', [])
      ->getNormalization();
    $this->assertNotEmpty($normalized['errors']);
    $this->assertArrayNotHasKey('data', $normalized);
    $this->assertEquals(400, $normalized['errors'][0]['status']);
    $this->assertEquals('Lorem', $normalized['errors'][0]['detail']);
    $this->assertEquals([
      'info' => [
        'href' => 'https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1',
      ],
      'via' => [
        'href' => 'http://localhost/',
      ],
    ], $normalized['errors'][0]['links']);
  }
  
  /**
   * Tests the message and exceptions when requesting a Label only resource.
   */
  public function testAliasFieldRouteException() : void {
    $this->assertSame('uid', $this->resourceTypeRepository
      ->getByTypeName('node--article')
      ->getPublicName('uid'));
    $this->assertSame('roles', $this->resourceTypeRepository
      ->getByTypeName('user--user')
      ->getPublicName('roles'));
    $resource_type_field_aliases = [
      'node--article' => [
        'uid' => 'author',
      ],
      'user--user' => [
        'roles' => 'user_roles',
      ],
    ];
    \Drupal::state()->set('jsonapi_test_resource_type_builder.resource_type_field_aliases', $resource_type_field_aliases);
    Cache::invalidateTags([
      'jsonapi_resource_types',
    ]);
    $this->assertSame('author', $this->resourceTypeRepository
      ->getByTypeName('node--article')
      ->getPublicName('uid'));
    $this->assertSame('user_roles', $this->resourceTypeRepository
      ->getByTypeName('user--user')
      ->getPublicName('roles'));
    // Create the request to fetch the articles and fetch included user.
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    $user = User::load($this->node
      ->getOwnerId());
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $user_resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('user', 'user');
    $resource_object_user = LabelOnlyResourceObject::createFromEntity($user_resource_type, $user);
    $includes = $this->includeResolver
      ->resolve($resource_object_user, 'user_roles');
    /** @var \Drupal\jsonapi\Normalizer\Value\CacheableNormalization $jsonapi_doc_object */
    $jsonapi_doc_object = $this->getNormalizer()
      ->normalize(new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
      $resource_object_user,
    ], 2), $includes, new LinkCollection([])), 'api_json', [
      'resource_type' => $resource_type,
      'account' => NULL,
      'sparse_fieldset' => [
        'node--article' => [
          'title',
          'node_type',
          'uid',
        ],
        'user--user' => [
          'user_roles',
        ],
      ],
      'include' => [
        'user_roles',
      ],
    ])
      ->getNormalization();
    $this->assertNotEmpty($jsonapi_doc_object['meta']['omitted']);
    foreach ($jsonapi_doc_object['meta']['omitted']['links'] as $key => $link) {
      if (str_starts_with($key, 'item--')) {
        // Ensure that resource link contains URL with the alias field.
        $resource_link = Url::fromUri('internal:/jsonapi/user/user/' . $user->uuid() . '/user_roles')
          ->setAbsolute()
          ->toString(TRUE);
        $this->assertEquals($resource_link->getGeneratedUrl(), $link['href']);
        $this->assertEquals("The current user is not allowed to view this relationship. The user only has authorization for the 'view label' operation.", $link['meta']['detail']);
      }
    }
  }
  
  /**
   * Tests normalize config.
   */
  public function testNormalizeConfig() : void {
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node_type', 'node_type');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->nodeType);
    $document_wrapper = new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
    ], 1), new NullIncludedData(), new LinkCollection([]));
    $jsonapi_doc_object = $this->getNormalizer()
      ->normalize($document_wrapper, 'api_json', [
      'resource_type' => $resource_type,
      'account' => NULL,
      'sparse_fieldset' => [
        'node_type--node_type' => [
          'description',
          'display_submitted',
        ],
      ],
    ]);
    $normalized = $jsonapi_doc_object->getNormalization();
    $this->assertSame([
      'description',
      'display_submitted',
    ], array_keys($normalized['data']['attributes']));
    $this->assertSame($normalized['data']['id'], NodeType::load('article')->uuid());
    $this->assertSame($normalized['data']['type'], 'node_type--node_type');
    // Make sure that the cache tags for the includes and the requested entities
    // are bubbling as expected.
    $this->assertSame([
      'config:node.type.article',
    ], $jsonapi_doc_object->getCacheTags());
  }
  
  /**
   * Try to POST a node and check if it exists afterwards.
   */
  public function testDenormalize() : void {
    $payload = '{"data":{"type":"article","attributes":{"title":"Testing article"}}}';
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    $node = $this->getNormalizer()
      ->denormalize(Json::decode($payload), NULL, 'api_json', [
      'resource_type' => $resource_type,
    ]);
    $this->assertInstanceOf(Node::class, $node);
    $this->assertSame('Testing article', $node->getTitle());
  }
  
  /**
   * Try to POST a node and check if it exists afterwards.
   */
  public function testDenormalizeUuid() : void {
    $configurations = [
      // Good data.
[
        [
          [
            $this->term2
              ->uuid(),
            $this->term1
              ->uuid(),
          ],
          $this->user2
            ->uuid(),
        ],
        [
          [
            $this->term2
              ->id(),
            $this->term1
              ->id(),
          ],
          $this->user2
            ->id(),
        ],
      ],
      // Good data, without any tags.
[
        [
          [],
          $this->user2
            ->uuid(),
        ],
        [
          [],
          $this->user2
            ->id(),
        ],
      ],
      // Bad data in first tag.
[
        [
          [
            'invalid-uuid',
            $this->term1
              ->uuid(),
          ],
          $this->user2
            ->uuid(),
        ],
        [
          [
            $this->term1
              ->id(),
          ],
          $this->user2
            ->id(),
        ],
        'taxonomy_term--tags:invalid-uuid',
      ],
      // Bad data in user and first tag.
[
        [
          [
            'invalid-uuid',
            $this->term1
              ->uuid(),
          ],
          'also-invalid-uuid',
        ],
        [
          [
            $this->term1
              ->id(),
          ],
          NULL,
        ],
        'user--user:also-invalid-uuid',
      ],
    ];
    foreach ($configurations as $configuration) {
      [$payload_data, $expected] = $this->denormalizeUuidProviderBuilder($configuration);
      $payload = Json::encode($payload_data);
      $resource_type = $this->container
        ->get('jsonapi.resource_type.repository')
        ->get('node', 'article');
      try {
        $node = $this->getNormalizer()
          ->denormalize(Json::decode($payload), NULL, 'api_json', [
          'resource_type' => $resource_type,
        ]);
      } catch (NotFoundHttpException $e) {
        $non_existing_resource_identifier = $configuration[2];
        $this->assertEquals("The resource identified by `{$non_existing_resource_identifier}` (given as a relationship item) could not be found.", $e->getMessage());
        continue;
      }
      /** @var \Drupal\node\Entity\Node $node */
      $this->assertInstanceOf(Node::class, $node);
      $this->assertSame('Testing article', $node->getTitle());
      if (!empty($expected['user_id'])) {
        $owner = $node->getOwner();
        $this->assertEquals($expected['user_id'], $owner->id());
      }
      $tags = $node->get('field_tags')
        ->getValue();
      if (!empty($expected['tag_ids'][0])) {
        $this->assertEquals($expected['tag_ids'][0], $tags[0]['target_id']);
      }
      else {
        $this->assertArrayNotHasKey(0, $tags);
      }
      if (!empty($expected['tag_ids'][1])) {
        $this->assertEquals($expected['tag_ids'][1], $tags[1]['target_id']);
      }
      else {
        $this->assertArrayNotHasKey(1, $tags);
      }
    }
  }
  
  /**
   * Tests denormalization for related resources with missing or invalid types.
   */
  public function testDenormalizeInvalidTypeAndNoType() : void {
    $payload_data = [
      'data' => [
        'type' => 'node--article',
        'attributes' => [
          'title' => 'Testing article',
          'id' => '33095485-70D2-4E51-A309-535CC5BC0115',
        ],
        'relationships' => [
          'uid' => [
            'data' => [
              'type' => 'user--user',
              'id' => $this->user2
                ->uuid(),
            ],
          ],
          'field_tags' => [
            'data' => [
              [
                'type' => 'foobar',
                'id' => $this->term1
                  ->uuid(),
              ],
            ],
          ],
        ],
      ],
    ];
    // Test relationship member with invalid type.
    $payload = Json::encode($payload_data);
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    try {
      $this->getNormalizer()
        ->denormalize(Json::decode($payload), NULL, 'api_json', [
        'resource_type' => $resource_type,
      ]);
      $this->fail('No assertion thrown for invalid type');
    } catch (BadRequestHttpException $e) {
      $this->assertEquals("Invalid type specified for related resource: 'foobar'", $e->getMessage());
    }
    // Test relationship member with no type.
    unset($payload_data['data']['relationships']['field_tags']['data'][0]['type']);
    $payload = Json::encode($payload_data);
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    try {
      $this->container
        ->get('jsonapi_test_normalizers_kernel.jsonapi_document_toplevel')
        ->denormalize(Json::decode($payload), NULL, 'api_json', [
        'resource_type' => $resource_type,
      ]);
      $this->fail('No assertion thrown for missing type');
    } catch (BadRequestHttpException $e) {
      $this->assertEquals("No type specified for related resource", $e->getMessage());
    }
  }
  
  /**
   * We cannot use a PHPUnit data provider because our data depends on $this.
   *
   * @param array $options
   *   Options for how to construct test data.
   *
   * @return array
   *   The test data.
   */
  protected function denormalizeUuidProviderBuilder(array $options) {
    [$input, $expected] = $options;
    [$input_tag_uuids, $input_user_uuid] = $input;
    [$expected_tag_ids, $expected_user_id] = $expected;
    $node = [
      [
        'data' => [
          'type' => 'node--article',
          'attributes' => [
            'title' => 'Testing article',
          ],
          'relationships' => [
            'uid' => [
              'data' => [
                'type' => 'user--user',
                'id' => $input_user_uuid,
              ],
            ],
            'field_tags' => [
              'data' => [],
            ],
          ],
        ],
      ],
      [
        'tag_ids' => $expected_tag_ids,
        'user_id' => $expected_user_id,
      ],
    ];
    if (isset($input_tag_uuids[0])) {
      $node[0]['data']['relationships']['field_tags']['data'][0] = [
        'type' => 'taxonomy_term--tags',
        'id' => $input_tag_uuids[0],
      ];
    }
    if (isset($input_tag_uuids[1])) {
      $node[0]['data']['relationships']['field_tags']['data'][1] = [
        'type' => 'taxonomy_term--tags',
        'id' => $input_tag_uuids[1],
      ];
    }
    return $node;
  }
  
  /**
   * Ensure that cacheability metadata is properly added.
   *
   * @param \Drupal\Core\Cache\CacheableMetadata $expected_metadata
   *   The expected cacheable metadata.
   */
  public function testCacheableMetadata(CacheableMetadata $expected_metadata) : void {
    $resource_type = $this->container
      ->get('jsonapi.resource_type.repository')
      ->get('node', 'article');
    $resource_object = ResourceObject::createFromEntity($resource_type, $this->node);
    $context = [
      'resource_type' => $resource_type,
      'account' => NULL,
    ];
    $jsonapi_doc_object = $this->getNormalizer()
      ->normalize(new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
    ], 1), new NullIncludedData(), new LinkCollection([])), 'api_json', $context);
    foreach ($expected_metadata->getCacheTags() as $tag) {
      $this->assertContains($tag, $jsonapi_doc_object->getCacheTags());
    }
    foreach ($expected_metadata->getCacheContexts() as $context) {
      $this->assertContains($context, $jsonapi_doc_object->getCacheContexts());
    }
    $this->assertSame($expected_metadata->getCacheMaxAge(), $jsonapi_doc_object->getCacheMaxAge());
  }
  
  /**
   * Provides test cases for asserting cacheable metadata behavior.
   */
  public static function cacheableMetadataProvider() : array {
    $cacheable_metadata = function ($metadata) {
      return CacheableMetadata::createFromRenderArray([
        '#cache' => $metadata,
      ]);
    };
    return [
      [
        $cacheable_metadata([
          'contexts' => [
            'languages:language_interface',
          ],
        ]),
      ],
    ];
  }
  
  /**
   * Helper to load the normalizer.
   */
  protected function getNormalizer() : JsonApiDocumentTopLevelNormalizer {
    $normalizer_service = $this->container
      ->get('jsonapi_test_normalizers_kernel.jsonapi_document_toplevel');
    // Simulate what happens when this normalizer service is used via the
    // serializer service, as it is meant to be used.
    $normalizer_service->setSerializer($this->container
      ->get('jsonapi.serializer'));
    return $normalizer_service;
  }
  
  /**
   * {@inheritdoc}
   */
  public static function jsonSchemaDataProvider() : array {
    return [
      'Empty collection top-level document' => [
        new JsonApiDocumentTopLevel(new ResourceObjectData([]), new NullIncludedData(), new LinkCollection([])),
      ],
    ];
  }
  
  /**
   * Test the generated resource object normalization against the schema.
   *
   * @legacy-covers \Drupal\jsonapi\Normalizer\ResourceObjectNormalizer::normalize
   * @legacy-covers \Drupal\jsonapi\Normalizer\ResourceObjectNormalizer::getNormalizationSchema
   */
  public function testResourceObjectSchema() : void {
    [, $resource_object] = $this->getTestContentEntityResource();
    $serializer = $this->container
      ->get('jsonapi.serializer');
    $context = [
      'account' => NULL,
    ];
    $format = $this->getJsonSchemaTestNormalizationFormat();
    $schema = $serializer->normalize($resource_object, 'json_schema', $context);
    $this->doCheckSchemaAgainstMetaSchema($schema);
    $normalized = json_decode(json_encode($serializer->normalize($resource_object, $format, $context)
      ->getNormalization()));
    $validator = $this->getValidator();
    $validator->validate($normalized, json_decode(json_encode($schema)));
    $this->assertSame([], $validator->getErrors(), 'Validation errors on object ' . print_r($normalized, TRUE) . ' with schema ' . print_r($schema, TRUE));
  }
  
  /**
   * Test the generated config resource object normalization against the schema.
   *
   * @legacy-covers \Drupal\jsonapi\Normalizer\ResourceObjectNormalizer::normalize
   * @legacy-covers \Drupal\jsonapi\Normalizer\ResourceObjectNormalizer::getNormalizationSchema
   */
  public function testConfigEntityResourceObjectSchema() : void {
    [, $resource_object] = $this->getTestConfigEntityResource();
    $serializer = $this->container
      ->get('jsonapi.serializer');
    $context = [
      'account' => NULL,
    ];
    $format = $this->getJsonSchemaTestNormalizationFormat();
    $schema = $serializer->normalize($resource_object, 'json_schema', $context);
    $this->doCheckSchemaAgainstMetaSchema($schema);
    $normalized = json_decode(json_encode($serializer->normalize($resource_object, $format, $context)
      ->getNormalization()));
    $validator = $this->getValidator();
    $validator->validate($normalized, json_decode(json_encode($schema)));
    $this->assertSame([], $validator->getErrors(), 'Validation errors on object ' . print_r($normalized, TRUE) . ' with schema ' . print_r($schema, TRUE));
  }
  
  /**
   * Tests the serialization of a top-level JSON:API document with a single resource.
   */
  public function testTopLevelResourceWithSingleResource() : void {
    [, $resource_object] = $this->getTestContentEntityResource();
    $serializer = $this->container
      ->get('jsonapi.serializer');
    $context = [
      'account' => NULL,
    ];
    $format = $this->getJsonSchemaTestNormalizationFormat();
    $topLevel = new JsonApiDocumentTopLevel(new ResourceObjectData([
      $resource_object,
    ]), new NullIncludedData(), new LinkCollection([]));
    $schema = $serializer->normalize($topLevel, 'json_schema', $context);
    $this->doCheckSchemaAgainstMetaSchema($schema);
    $normalized = json_decode(json_encode($serializer->normalize($topLevel, $format, $context)
      ->getNormalization()));
    $validator = $this->getValidator();
    $validator->validate($normalized, json_decode(json_encode($schema)));
    $this->assertSame([], $validator->getErrors(), 'Validation errors on object ' . print_r($normalized, TRUE) . ' with schema ' . print_r($schema, TRUE));
  }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Member alias Overriden Title Overrides
AssertContentTrait::$content protected property The current raw content.
AssertContentTrait::$drupalSettings protected property The drupalSettings value from the current raw $content.
AssertContentTrait::$elements protected property The XML structure parsed from the current raw $content. 1
AssertContentTrait::$plainTextContent protected property The plain-text content of raw $content (text nodes).
AssertContentTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertContentTrait::assertFieldById Deprecated protected function Asserts that a field exists with the given ID and value.
AssertContentTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertContentTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertContentTrait::assertFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is checked.
AssertContentTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertContentTrait::assertLink protected function Passes if a link with the specified label is found.
AssertContentTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertContentTrait::assertNoDuplicateIds Deprecated protected function Asserts that each HTML ID is used for just a single element.
AssertContentTrait::assertNoEscaped protected function Passes if raw text IS NOT found escaped on loaded page, fail otherwise.
AssertContentTrait::assertNoField Deprecated protected function Asserts that a field does not exist with the given name or ID.
AssertContentTrait::assertNoFieldById Deprecated protected function Asserts that a field does not exist with the given ID and value.
AssertContentTrait::assertNoFieldByName Deprecated protected function Asserts that a field does not exist with the given name and value.
AssertContentTrait::assertNoFieldByXPath Deprecated protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertContentTrait::assertNoFieldChecked Deprecated protected function Asserts that a checkbox field in the current page is not checked.
AssertContentTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertContentTrait::assertNoLinkByHref Deprecated protected function Passes if a link containing a given href (part) is not found.
AssertContentTrait::assertNoLinkByHrefInMainRegion Deprecated protected function Passes if a link containing a given href is not found in the main region.
AssertContentTrait::assertNoOption Deprecated protected function Asserts that a select option in the current page does not exist.
AssertContentTrait::assertNoOptionSelected Deprecated protected function Asserts that a select option in the current page is not checked.
AssertContentTrait::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
AssertContentTrait::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
AssertContentTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text.
AssertContentTrait::assertNoTitle protected function Pass if the page title is not the given string.
AssertContentTrait::assertNoUniqueText Deprecated protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertContentTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertOptionByText Deprecated protected function Asserts that a select option with the visible text exists.
AssertContentTrait::assertOptionSelected Deprecated protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionSelectedWithDrupalSelector Deprecated protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionWithDrupalSelector protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertContentTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertContentTrait::assertText protected function Passes if the page (with HTML stripped) contains the text.
AssertContentTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertContentTrait::assertTextPattern Deprecated protected function Asserts that a Perl regex pattern is found in the plain-text content.
AssertContentTrait::assertThemeOutput protected function Asserts themed output.
AssertContentTrait::assertTitle protected function Pass if the page title is the given string.
AssertContentTrait::assertUniqueText Deprecated protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertContentTrait::assertUniqueTextHelper Deprecated protected function Helper for assertUniqueText and assertNoUniqueText.
AssertContentTrait::buildXPathQuery protected function Builds an XPath query.
AssertContentTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertContentTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
AssertContentTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertContentTrait::getDrupalSettings protected function Gets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::getRawContent protected function Gets the current raw content.
AssertContentTrait::getSelectedItem protected function Get the selected value from a select field.
AssertContentTrait::getTextContent protected function Retrieves the plain-text content from the current raw content.
AssertContentTrait::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
AssertContentTrait::removeWhiteSpace protected function Removes all white-space between HTML tags from the raw content.
AssertContentTrait::setDrupalSettings protected function Sets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::setRawContent protected function Sets the raw content (e.g. HTML).
AssertContentTrait::xpath protected function Performs an xpath search on the contents of the internal browser.
ConfigTestTrait::configImporter protected function Returns a ConfigImporter object to import test configuration.
ConfigTestTrait::copyConfig protected function Copies configuration objects from source storage to target storage.
DrupalTestCaseTrait::checkErrorHandlerOnTearDown public function Checks the test error handler after test execution. 1
EntityReferenceFieldCreationTrait::createEntityReferenceField protected function Creates a field of an entity reference field storage on the specified bundle.
ExpectDeprecationTrait::expectDeprecation Deprecated public function Adds an expected deprecation.
ExpectDeprecationTrait::regularExpressionForFormatDescription private function
ExtensionListTestTrait::getModulePath protected function Gets the path for the specified module.
ExtensionListTestTrait::getThemePath protected function Gets the path for the specified theme.
ImageFieldCreationTrait::createImageField protected function Create a new image field.
JsonApiJsonSchemaTestTrait::getJsonSchemaTestNormalizationFormat protected function Format that should be used when performing test normalizations. Overrides JsonSchemaTestTrait::getJsonSchemaTestNormalizationFormat
JsonApiJsonSchemaTestTrait::getNormalizationForValue protected function
JsonApiJsonSchemaTestTrait::getValidator protected function Get the JSON Schema Validator. Overrides JsonSchemaTestTrait::getValidator
JsonapiKernelTestBase::createTextField protected function Creates a field of a text field storage on the bundle.
JsonApiTopLevelResourceNormalizerTest::$file private property
JsonApiTopLevelResourceNormalizerTest::$includeResolver protected property The include resolver.
JsonApiTopLevelResourceNormalizerTest::$modules protected static property Modules to install. Overrides JsonapiKernelTestBase::$modules
JsonApiTopLevelResourceNormalizerTest::$node protected property A node to normalize.
JsonApiTopLevelResourceNormalizerTest::$nodeType protected property The node type.
JsonApiTopLevelResourceNormalizerTest::$resourceTypeRepository protected property The JSON:API resource type repository under test.
JsonApiTopLevelResourceNormalizerTest::$term1 protected property A term.
JsonApiTopLevelResourceNormalizerTest::$term2 protected property A term.
JsonApiTopLevelResourceNormalizerTest::$user protected property A user to normalize.
JsonApiTopLevelResourceNormalizerTest::$user2 protected property A user.
JsonApiTopLevelResourceNormalizerTest::$vocabulary protected property A vocabulary.
JsonApiTopLevelResourceNormalizerTest::cacheableMetadataProvider public static function Provides test cases for asserting cacheable metadata behavior.
JsonApiTopLevelResourceNormalizerTest::denormalizeUuidProviderBuilder protected function We cannot use a PHPUnit data provider because our data depends on $this.
JsonApiTopLevelResourceNormalizerTest::getNormalizer protected function Helper to load the normalizer. Overrides JsonSchemaTestTrait::getNormalizer
JsonApiTopLevelResourceNormalizerTest::getTestConfigEntityResource protected function Get a test resource type, resource object and includes for config entity.
JsonApiTopLevelResourceNormalizerTest::getTestContentEntityResource protected function Get a test resource type, resource object and includes.
JsonApiTopLevelResourceNormalizerTest::jsonSchemaDataProvider public static function Data provider for ::testNormalizedValuesAgainstJsonSchema. Overrides JsonSchemaTestTrait::jsonSchemaDataProvider
JsonApiTopLevelResourceNormalizerTest::setUp protected function Overrides KernelTestBase::setUp
JsonApiTopLevelResourceNormalizerTest::tearDown protected function Overrides KernelTestBase::tearDown
JsonApiTopLevelResourceNormalizerTest::testAliasFieldRouteException public function Tests the message and exceptions when requesting a Label only resource.
JsonApiTopLevelResourceNormalizerTest::testCacheableMetadata public function Ensure that cacheability metadata is properly added.
JsonApiTopLevelResourceNormalizerTest::testConfigEntityResourceObjectSchema public function Test the generated config resource object normalization against the schema.
JsonApiTopLevelResourceNormalizerTest::testDenormalize public function Try to POST a node and check if it exists afterwards.
JsonApiTopLevelResourceNormalizerTest::testDenormalizeInvalidTypeAndNoType public function Tests denormalization for related resources with missing or invalid types.
JsonApiTopLevelResourceNormalizerTest::testDenormalizeUuid public function Try to POST a node and check if it exists afterwards.
JsonApiTopLevelResourceNormalizerTest::testNormalize public function Tests normalize.
JsonApiTopLevelResourceNormalizerTest::testNormalizeConfig public function Tests normalize config.
JsonApiTopLevelResourceNormalizerTest::testNormalizeException public function Tests normalize exception.
JsonApiTopLevelResourceNormalizerTest::testNormalizeUuid public function Tests normalize uuid.
JsonApiTopLevelResourceNormalizerTest::testResourceObjectSchema public function Test the generated resource object normalization against the schema.
JsonApiTopLevelResourceNormalizerTest::testTopLevelResourceWithSingleResource public function Tests the serialization of a top-level JSON:API document with a single resource.
JsonSchemaTestTrait::doCheckSchemaAgainstMetaSchema protected function Check a schema is valid against the meta-schema.
JsonSchemaTestTrait::doProphesize public function Method to make prophecy public for use in data provider closures.
JsonSchemaTestTrait::doTestJsonSchemaIsValid public function Validate the normalizer's JSON schema.
JsonSchemaTestTrait::getNormalizationForValue protected function Get the normalization for a value. Aliased as: parentGetNormalizationForValue
JsonSchemaTestTrait::supportedTypesDataProvider public static function
JsonSchemaTestTrait::testNormalizedValuesAgainstJsonSchema public function Test normalized values against the JSON schema.
JsonSchemaTestTrait::testSupportedTypesSchemaIsValid public function Test that a valid schema is returned for the explicitly supported types.
KernelTestBase::$classLoader protected property The class loader.
KernelTestBase::$configImporter protected property The configuration importer. 6
KernelTestBase::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking. 4
KernelTestBase::$container protected property The test container.
KernelTestBase::$databasePrefix protected property The test database prefix.
KernelTestBase::$keyValue protected property The key_value service that must persist between container rebuilds.
KernelTestBase::$root protected property The app root.
KernelTestBase::$siteDirectory protected property The relative path to the test site directory.
KernelTestBase::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 10
KernelTestBase::$usesSuperUserAccessPolicy protected property Set to TRUE to make user 1 a super user. 1
KernelTestBase::$vfsRoot protected property The virtual filesystem root directory.
KernelTestBase::assertPostConditions protected function 1
KernelTestBase::bootEnvironment protected function Bootstraps a basic test environment.
KernelTestBase::bootKernel protected function Bootstraps a kernel for a test. 1
KernelTestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test. 2
KernelTestBase::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
KernelTestBase::getDatabaseConnectionInfo protected function Returns the Database connection info to be used for this test. 3
KernelTestBase::getDatabasePrefix public function Gets the database prefix used for test isolation.
KernelTestBase::getExtensionsForModules private function Returns Extension objects for $modules to install.
KernelTestBase::getModulesToEnable protected static function Returns the modules to install for this test.
KernelTestBase::initFileCache protected function Initializes the FileCache component.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs database tables from a module schema definition.
KernelTestBase::register public function Registers test-specific services. Overrides ServiceProviderInterface::register 38
KernelTestBase::render protected function Renders a render array. 1
KernelTestBase::setDebugDumpHandler public static function Registers the dumper CLI handler when the DebugDump extension is enabled.
KernelTestBase::setInstallProfile protected function Sets the install profile and rebuilds the container to update it.
KernelTestBase::setSetting protected function Sets an in-memory Settings variable.
KernelTestBase::setUpFilesystem protected function Sets up the filesystem, so things like the file directory. 3
KernelTestBase::tearDownCloseDatabaseConnection public function Additional tear down method to close the connection at the end.
KernelTestBase::vfsDump protected function Dumps the current state of the virtual filesystem to STDOUT.
KernelTestBase::__construct public function
KernelTestBase::__sleep public function Prevents serializing any properties.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
StorageCopyTrait::replaceStorageContents protected static function Copy the configuration from one storage to another and remove stale items.
TestRequirementsTrait::getDrupalRoot protected static function Returns the Drupal root directory.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.