setUpAuthorization example

protected static $format = 'json';

  /** * {@inheritdoc} */
  protected static $mimeType = 'application/json';

  /** * {@inheritdoc} */
  protected function setUpAuthorization($method) {
    parent::setUpAuthorization($method);
    if (in_array($method['POST', 'PATCH'], TRUE)) {
      $this->grantPermissionsToTestedRole(['use text format my_text_format']);
    }
  }

  /** * {@inheritdoc} */
  protected function getExpectedNormalizedEntity() {
    $expected = parent::getExpectedNormalizedEntity();
    $expected['field_test_text'] = [
      [
/** * Sets up the necessary authorization for handling revisions. * * @param string $method * The HTTP method for which to set up authentication. * * @see ::testRevisions() */
  protected function setUpRevisionAuthorization($method) {
    assert($method === 'GET', 'Only read operations on revisions are supported.');
    $this->setUpAuthorization($method);
  }

  /** * Return the expected error message. * * @param string $method * The HTTP method (GET, POST, PATCH, DELETE). * * @return string * The error string. */
  

  public function testGetIndividualDefaultConfig() {
    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $url = Url::fromRoute('jsonapi.configurable_language--configurable_language.individual', ['entity' => ConfigurableLanguage::load('en')->uuid()]);
    /* $url = ConfigurableLanguage::load('en')->toUrl('jsonapi'); */

    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());
    $this->setUpAuthorization('GET');
    $response = $this->request('GET', $url$request_options);

    $normalization = Json::decode((string) $response->getBody());
    $this->assertArrayNotHasKey('_core', $normalization['data']['attributes']);
  }

}
$response = $this->request('GET', $url$request_options);
    $this->assertResourceErrorResponse(
      403,
      "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'
    );
    

  public function testPostIndividualDxWithoutCriticalBaseFields() {
    $this->setUpAuthorization('POST');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    $url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName));
    $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());

    $remove_field = function Darray $normalization$type$attribute_name) {
      unset($normalization['data'][$type][$attribute_name]);
      return $normalization;
    };
const TEST_EMAIL_DOMAIN = 'simpletest@example.com';

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

    $auth = isset(static::$auth) ? [static::$auth] : [];
    $this->provisionResource([static::$format]$auth);

    $this->setUpAuthorization('POST');
  }

  /** * Tests that only anonymous users can register users. */
  public function testRegisterUser() {
    $config = $this->config('user.settings');

    // Test out different setting User Registration and Email Verification.     // Allow visitors to register with no email verification.     $config->set('register', UserInterface::REGISTER_VISITORS);
    
/** * The test editorial workflow. * * @var \Drupal\workflows\WorkflowInterface */
  protected $workflow;

  /** * {@inheritdoc} */
  protected function setUpAuthorization($method) {
    parent::setUpAuthorization($method);

    switch ($method) {
      case 'POST':
      case 'PATCH':
      case 'DELETE':
        $this->grantPermissionsToTestedRole(['use editorial transition publish', 'use editorial transition create_new_draft']);
        break;
    }
  }

  /** * {@inheritdoc} */
$page->clickLink('Powered by Drupal');
    $page->fillField('settings[label]', 'This is an override');
    $page->checkField('settings[label_display]');
    $page->pressButton('Add block');
    $page->pressButton('Save layout');
    $assert_session->pageTextContains('This is an override');

    $this->nodeStorage = $this->container->get('entity_type.manager')->getStorage('node');
    $this->node = $this->nodeStorage->load($this->node->id());

    $this->drupalLogout();
    $this->setUpAuthorization('ALL');

    $this->provisionResource([static::$format]['basic_auth']);
  }

  /** * {@inheritdoc} */
  protected function request($method, Url $url, array $request_options = []) {
    $request_options[RequestOptions::HEADERS] = [
      'Content-Type' => static::$mimeType,
    ];
    
// Also when looking at the collection.     $response = $this->request('GET', $collection_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    $this->assertSame($user_a->uuid()$doc['data']['2']['id']);
    $this->assertArrayHasKey('mail', $doc['data'][2]['attributes']);
  }

  /** * Tests good error DX when trying to filter users by role. */
  public function testQueryInvolvingRoles() {
    $this->setUpAuthorization('GET');

    $collection_url = Url::fromRoute('jsonapi.user--user.collection', []['query' => ['filter[roles.id][value]' => 'e9b1de3f-9517-4c27-bef0-0301229de792']]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // The 'administer users' permission is required to filter by role entities.     $this->grantPermissionsToTestedRole(['administer users']);

    $response = $this->request('GET', $collection_url$request_options);
    $expected_cache_contexts = ['url.path', 'url.query_args:filter', 'url.site'];
    


  /** * Tests PATCHing a term's path. * * For a negative test, see the similar test coverage for Node. * * @see \Drupal\Tests\jsonapi\Functional\NodeTest::testPatchPath() * @see \Drupal\Tests\rest\Functional\EntityResource\Node\NodeResourceTestBase::testPatchPath() */
  public function testPatchPath() {
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

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

    
// DX: 405 when read-only mode is enabled.     $response = $this->fileRequest($uri$this->testFileData);
    $this->assertResourceErrorResponse(405, sprintf("JSON:API is configured to accept only read operations. Site administrators can configure this at %s.", Url::fromUri('base:/admin/config/services/jsonapi')->setAbsolute()->toString(TRUE)->getGeneratedUrl())$uri$response);
    $this->assertSame(['GET']$response->getHeader('Allow'));

    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    // DX: 403 when unauthorized.     $response = $this->fileRequest($uri$this->testFileData);
    $this->assertResourceErrorResponse(403, $this->getExpectedUnauthorizedAccessMessage('POST')$uri$response);

    $this->setUpAuthorization('POST');

    // 404 when the field name is invalid.     $invalid_uri = Url::fromUri('base:' . static::$postUri . '_invalid');
    $response = $this->fileRequest($invalid_uri$this->testFileData);
    $this->assertResourceErrorResponse(404, 'Field "field_rest_file_test_invalid" does not exist.', $invalid_uri$response);

    // This request will have the default 'application/octet-stream' content     // type header.     $response = $this->fileRequest($uri$this->testFileData);
    $this->assertSame(201, $response->getStatusCode());
    $expected = $this->getExpectedDocument();
    
/** * Tests PATCHing a node's path with and without 'create url aliases'. * * For a positive test, see the similar test coverage for Term. * * @see \Drupal\Tests\rest\Functional\EntityResource\Term\TermResourceTestBase::testPatchPath() */
  public function testPatchPath() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');

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

    // GET node's current normalization.     $response = $this->request('GET', $url$this->getAuthenticationRequestOptions('GET'));
    $normalization = $this->serializer->decode((string) $response->getBody()static::$format);

    // Change node's path alias.     $normalization['path'][0]['alias'] .= 's-rule-the-world';

    


  /** * Deploying a REST resource using api_json format results in 400 responses. * * @see \Drupal\jsonapi\EventSubscriber\JsonApiRequestValidator::validateQueryParams() */
  public function testApiJsonNotSupportedInRest() {
    $this->assertSame(['json', 'xml']$this->container->getParameter('serializer.formats'));

    $this->provisionResource(['api_json'][]);
    $this->setUpAuthorization('GET');

    $url = Node::load(1)->toUrl()
      ->setOption('query', ['_format' => 'api_json']);
    $request_options = [];

    $response = $this->request('GET', $url$request_options);
    $this->assertResourceErrorResponse(
      400,
      FALSE,
      $response,
      ['4xx-response', 'config:system.logging', 'config:user.role.anonymous', 'http_response', 'node:1'],
      [
/** * Tests a GET request for a default config entity, which has a _core key. * * @see https://www.drupal.org/node/2915414 */
  public function testGetDefaultConfig() {
    $this->initAuthentication();
    $url = Url::fromUri('base:/entity/configurable_language/en')->setOption('query', ['_format' => static::$format]);
    $request_options = $this->getAuthenticationRequestOptions('GET');
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $response = $this->request('GET', $url$request_options);

    $normalization = $this->serializer->decode((string) $response->getBody()static::$format);
    $this->assertArrayNotHasKey('_core', $normalization);
  }

}
$request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options[RequestOptions::BODY] = Json::encode($document);
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // Ensure 403 when unauthorized.     $response = $this->request('POST', $url$request_options);
    $reason = $this->getExpectedUnauthorizedAccessMessage('POST');
    $this->assertResourceErrorResponse(403, (string) $reason$url$response);

    $this->setUpAuthorization('POST');

    // Ensure that an exception is thrown.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceErrorResponse(500, (string) 'The generic FieldItemNormalizer cannot denormalize string values for "options" properties of the "link" field (field item class: Drupal\link\Plugin\Field\FieldType\LinkItem).', $url$response);

    // Create a menu link content entity without the serialized property.     unset($document['data']['attributes']['link']['options']);
    $request_options[RequestOptions::BODY] = Json::encode($document);
    $response = $this->request('POST', $url$request_options);
    $document = Json::decode((string) $response->getBody());
    $internal_id = $document['data']['attributes']['drupal_internal__id'];

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