assertResourceResponse example

    // asserting the 403 response, assert that the stored path alias remains     // unchanged.     $response = $this->request('PATCH', $url$request_options);
    $this->assertSame('/llama', $this->entityStorage->loadUnchanged($this->entity->id())->get('path')->alias);
    $this->assertResourceErrorResponse(403, "Access denied on updating field 'path'. " . static::$patchProtectedFieldNames['path']$response);

    // Grant permission to create URL aliases.     $this->grantPermissionsToTestedRole(['create url aliases']);

    // Repeat PATCH request: 200.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);
    $updated_normalization = $this->serializer->decode((string) $response->getBody()static::$format);
    $this->assertSame($normalization['path']$updated_normalization['path']);
  }

}
$request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    // DX: 422 when changing email while providing a wrong password.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the Email.\n", $response, FALSE, FALSE, FALSE, FALSE);

    $normalization['pass'] = [['existing' => $this->account->passRaw]];
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    // 200 for well-formed request.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);

    // Test case 2: changing password.     $normalization = $original_normalization;
    $new_password = $this->randomString();
    $normalization['pass'] = [['value' => $new_password]];
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    // DX: 422 when changing password without providing the current password.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\npass: Your current password is missing or incorrect; it's required to change the Password.\n", $response, FALSE, FALSE, FALSE, FALSE);

    
$request_options[RequestOptions::BODY] = Json::encode($normalization);

    // DX: 422 when changing email while providing a wrong password.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(422, 'mail: Your current password is missing or incorrect; it\'s required to change the Email.', NULL, $response, '/data/attributes/mail');

    $normalization['data']['attributes']['pass']['existing'] = $this->account->passRaw;
    $request_options[RequestOptions::BODY] = Json::encode($normalization);

    // 200 for well-formed request.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);

    // Test case 2: changing password.     $normalization = Json::decode((string) $response->getBody());
    $normalization['data']['attributes']['mail'] = 'new-email@example.com';
    $new_password = $this->randomString();
    $normalization['data']['attributes']['pass']['value'] = $new_password;
    $request_options[RequestOptions::BODY] = Json::encode($normalization);

    // DX: 422 when changing password without providing the current password.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(422, 'pass: Your current password is missing or incorrect; it\'s required to change the Password.', NULL, $response, '/data/attributes/pass');

    
$request_options[RequestOptions::BODY] = Json::encode($normalization);

    // PATCH request: 403 when creating URL aliases unauthorized.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(403, "The current user is not allowed to PATCH the selected field (path). The following permissions are required: 'create url aliases' OR 'administer url aliases'.", $url$response, '/data/attributes/path');

    // Grant permission to create URL aliases.     $this->grantPermissionsToTestedRole(['create url aliases']);

    // Repeat PATCH request: 200.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);
    $updated_normalization = Json::decode((string) $response->getBody());
    $this->assertSame($normalization['data']['attributes']['path']['alias']$updated_normalization['data']['attributes']['path']['alias']);
  }

  /** * {@inheritdoc} */
  public function testGetIndividual() {
    parent::testGetIndividual();

    $this->assertCacheableNormalizations();
    

  protected function registerUser($name$include_password = TRUE, $include_email = TRUE) {
    // Verify that an anonymous user can register.     $response = $this->registerRequest($name$include_password$include_email);
    $this->assertResourceResponse(200, FALSE, $response);
    $user = user_load_by_name($name);
    $this->assertNotEmpty($user, 'User was create as expected');
    return $user;
  }

  /** * Make a REST user registration request. * * @param string $name * The name. * @param bool $include_password * Include the password? * @param bool $include_email * Include the email? * * @return \Psr\Http\Message\ResponseInterface * Return the Response. */
"The 'restful get dblog' permission is required.",
      $response,
      ['4xx-response', 'http_response'],
      ['user.permissions']
    );

    // Create a user account that has the required permissions to read     // the watchdog resource via the REST API.     $this->setUpAuthorization('GET');

    $response = $this->request('GET', $url$request_options);
    $this->assertResourceResponse(
      200,
      FALSE,
      $response,
      ['config:rest.resource.dblog', 'http_response'],
      ['user.permissions'],
      FALSE,
      'MISS'
    );
    $log = Json::decode((string) $response->getBody());
    $this->assertEquals($id$log['wid'], 'Log ID is correct.');
    $this->assertEquals('rest', $log['type'], 'Type of log message is correct.');
    
// Create request.     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());
    $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument());

    $url = Url::fromRoute('jsonapi.comment--comment.collection.post');

    // Status should be FALSE when posting as anonymous.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertFalse(Json::decode((string) $response->getBody())['data']['attributes']['status']);
    $this->assertFalse($this->entityStorage->loadUnchanged(2)->isPublished());

    // Grant anonymous permission to skip comment approval.     $this->grantPermissionsToTestedRole(['skip comment approval']);

    // Status must be TRUE when posting as anonymous and skip comment approval.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue(Json::decode((string) $response->getBody())['data']['attributes']['status']);
    $this->assertTrue($this->entityStorage->loadUnchanged(3)->isPublished());
  }
$this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('rest.entity.entity_test.POST')
      ->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions('POST'));

    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    $this->assertSame([
      [
        'target_id' => '1',
        'display' => NULL,
        'description' => "The most fascinating file ever!",
      ],
    ], EntityTest::load(2)->get('field_rest_file_test')->getValue());
  }

  /** * Returns the normalized POST entity referencing the uploaded file. * * @return array * * @see ::testPostFileUpload() * @see \Drupal\Tests\rest\Functional\EntityResource\EntityTest\EntityTestResourceTestBase::getNormalizedPostEntity() */
// DX: 403 because unauthorized.     $url->setOption('query', ['_format' => static::$format]);
    $response = $this->request('GET', $url$request_options);
    $this->assertResourceErrorResponse(403, $this->getExpectedUnauthorizedAccessMessage('GET')$response$expected_403_cacheability->getCacheTags()$expected_403_cacheability->getCacheContexts()static::$auth ? FALSE : 'MISS', FALSE);
    $this->assertArrayNotHasKey('Link', $response->getHeaders());

    $this->setUpAuthorization('GET');

    // 200 for well-formed HEAD request.     $response = $this->request('HEAD', $url$request_options);
    $is_cacheable_by_dynamic_page_cache = empty(array_intersect(['user', 'session']$this->getExpectedCacheContexts()));
    $this->assertResourceResponse(200, '', $response$this->getExpectedCacheTags()$this->getExpectedCacheContexts()static::$auth ? FALSE : 'MISS', $is_cacheable_by_dynamic_page_cache ? 'MISS' : 'UNCACHEABLE');
    $head_headers = $response->getHeaders();

    // 200 for well-formed GET request. Page Cache hit because of HEAD request.     // Same for Dynamic Page Cache hit.     $response = $this->request('GET', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response$this->getExpectedCacheTags()$this->getExpectedCacheContexts()static::$auth ? FALSE : 'HIT', $is_cacheable_by_dynamic_page_cache ? (static::$auth ? 'HIT' : 'MISS') : 'UNCACHEABLE');
    // Assert that Dynamic Page Cache did not store a ResourceResponse object,     // which needs serialization after every cache hit. Instead, it should     // contain a flattened response. Otherwise performance suffers.     // @see \Drupal\rest\EventSubscriber\ResourceResponseSubscriber::flattenResponse()     $cache_items = $this->container->get('database')
      
// Change term's path alias.     $normalization['path'][0]['alias'] .= 's-rule-the-world';

    // Create term PATCH request.     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('PATCH'));
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    // PATCH request: 200.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);
    $updated_normalization = $this->serializer->decode((string) $response->getBody()static::$format);
    $this->assertSame($normalization['path']$updated_normalization['path']);
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheTags() {
    return Cache::mergeTags(parent::getExpectedCacheTags()['config:filter.format.plain_text', 'config:filter.settings']);
  }

  

    if ($pointer !== FALSE) {
      $expected_error['source']['pointer'] = $pointer;
    }

    $expected_document = [
      'jsonapi' => static::$jsonApiMember,
      'errors' => [
        0 => $expected_error,
      ],
    ];
    $this->assertResourceResponse($expected_status_code$expected_document$response$expected_cache_tags$expected_cache_contexts$expected_page_cache_header_value$expected_dynamic_page_cache_header_value);
  }

  /** * Makes the JSON:API document violate the spec by omitting the resource type. * * @param array $document * A JSON:API document. * * @return array * The same JSON:API document, without its resource type. */
  
$menu_link->save();

    // Fetch the link.     unset($request_options[RequestOptions::BODY]);
    $url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName)['entity' => $document['data']['id']]);
    $response = $this->request('GET', $url$request_options);
    $response_body = (string) $response->getBody();

    // Ensure that the entity can be updated using a response document.     $request_options[RequestOptions::BODY] = $response_body;
    $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, Json::decode($response_body)$response);
  }

}
    $response = $this->request('GET', $url$request_options);
    $normalization = Json::decode((string) $response->getBody());

    // Change term's path alias.     $normalization['data']['attributes']['path']['alias'] .= 's-rule-the-world';

    // Create term PATCH request.     $request_options[RequestOptions::BODY] = Json::encode($normalization);

    // PATCH request: 200.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceResponse(200, FALSE, $response);
    $updated_normalization = Json::decode((string) $response->getBody());
    $this->assertSame($normalization['data']['attributes']['path']['alias']$updated_normalization['data']['attributes']['path']['alias']);
  }

  /** * {@inheritdoc} */
  protected function getExpectedCacheTags(array $sparse_fieldset = NULL) {
    $tags = parent::getExpectedCacheTags($sparse_fieldset);
    if ($sparse_fieldset === NULL || in_array('description', $sparse_fieldset)) {
      $tags = Cache::mergeTags($tags['config:filter.format.plain_text', 'config:filter.settings']);
    }
/** * Tests that the layout override field is not normalized. */
  public function testOverrideField() {
    $this->assertCount(1, $this->node->get(OverridesSectionStorage::FIELD_NAME));

    // Make a GET request and ensure override field is not included.     $response = $this->request(
      'GET',
      Url::fromRoute('rest.entity.node.GET', ['node' => $this->node->id()])
    );
    $this->assertResourceResponse(
      200,
      FALSE,
      $response,
      [
        'config:filter.format.plain_text',
        'config:rest.resource.entity.node',
        'http_response',
        'node:1',
      ],
      [
        'languages:language_interface',
        
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('POST'));
    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);

    $url = $this->getEntityResourcePostUrl()->setOption('query', ['_format' => static::$format]);

    // Status should be FALSE when posting as anonymous.     $response = $this->request('POST', $url$request_options);
    $unserialized = $this->serializer->deserialize((string) $response->getBody()get_class($this->entity)static::$format);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertFalse($unserialized->isPublished());

    // Grant anonymous permission to skip comment approval.     $this->grantPermissionsToTestedRole(['skip comment approval']);

    // Status should be TRUE when posting as anonymous and skip comment approval.     $response = $this->request('POST', $url$request_options);
    $unserialized = $this->serializer->deserialize((string) $response->getBody()get_class($this->entity)static::$format);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($unserialized->isPublished());
  }

  
Home | Imprint | This part of the site doesn't use cookies.