You are here

public function NodeTest::testGetIndividual in JSON:API 8.2

Same name and namespace in other branches
  1. 8 tests/src/Functional/NodeTest.php \Drupal\Tests\jsonapi\Functional\NodeTest::testGetIndividual()

Tests GETting an individual resource, plus edge cases to ensure good DX.

Overrides ResourceTestBase::testGetIndividual

File

tests/src/Functional/NodeTest.php, line 301

Class

NodeTest
JSON:API integration test for the "Node" content entity type.

Namespace

Drupal\Tests\jsonapi\Functional

Code

public function testGetIndividual() {
  parent::testGetIndividual();

  // Unpublish node.
  $this->entity
    ->setUnpublished()
    ->save();

  // @todo Remove line below in favor of commented line in https://www.drupal.org/project/jsonapi/issues/2878463.
  $url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName), [
    'entity' => $this->entity
      ->uuid(),
  ]);

  /* $url = $this->entity->toUrl('jsonapi'); */
  $request_options = $this
    ->getAuthenticationRequestOptions();

  // 403 when accessing own unpublished node.
  $response = $this
    ->request('GET', $url, $request_options);

  // @todo Remove $expected + assertResourceResponse() in favor of the commented line below once https://www.drupal.org/project/jsonapi/issues/2943176 lands.
  $expected_document = [
    'jsonapi' => static::$jsonApiMember,
    'errors' => [
      [
        'title' => 'Forbidden',
        'status' => '403',
        'detail' => 'The current user is not allowed to GET the selected resource.',
        'links' => [
          'info' => [
            'href' => HttpExceptionNormalizer::getInfoUrl(403),
          ],
          'via' => [
            'href' => $url
              ->setAbsolute()
              ->toString(),
          ],
        ],
        'source' => [
          'pointer' => '/data',
        ],
      ],
    ],
  ];
  $this
    ->assertResourceResponse(403, $expected_document, $response, [
    '4xx-response',
    'http_response',
    'node:1',
  ], [
    'url.query_args:resourceVersion',
    'url.site',
    'user.permissions',
  ], FALSE, 'MISS');

  /* $this->assertResourceErrorResponse(403, 'The current user is not allowed to GET the selected resource.', $response, '/data'); */

  // 200 after granting permission.
  $this
    ->grantPermissionsToTestedRole([
    'view own unpublished content',
  ]);
  $response = $this
    ->request('GET', $url, $request_options);

  // The response varies by 'user', causing the 'user.permissions' cache
  // context to be optimized away.
  $expected_cache_contexts = Cache::mergeContexts($this
    ->getExpectedCacheContexts(), [
    'user',
  ]);
  $expected_cache_contexts = array_diff($expected_cache_contexts, [
    'user.permissions',
  ]);
  $this
    ->assertResourceResponse(200, FALSE, $response, $this
    ->getExpectedCacheTags(), $expected_cache_contexts, FALSE, 'UNCACHEABLE');
}