initAuthentication example

->save();

    // Set TextItemBase field's value for testing, using the given text format.     $value = [
      'value' => $this->randomString(),
    ];
    if ($text_format_id !== FALSE) {
      $value['format'] = $text_format_id;
    }
    $this->entity->set('field_test_text', $value)->save();

    $this->initAuthentication();
    $url = $this->getEntityResourceUrl();
    $url->setOption('query', ['_format' => static::$format]);
    $request_options = $this->getAuthenticationRequestOptions('GET');
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $response = $this->request('GET', $url$request_options);
    $expected_cache_tags = Cache::mergeTags($expected_cache_tags, parent::getExpectedCacheTags());
    $this->assertEqualsCanonicalizing($expected_cache_tagsexplode(' ', $response->getHeader('X-Drupal-Cache-Tags')[0]));
  }

  public function providerTestGetWithFormat() {
    
'id' => 'file.upload',
      'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
      'configuration' => [
        'methods' => ['POST'],
        'formats' => [static::$format],
        'authentication' => isset(static::$auth) ? [static::$auth] : [],
      ],
      'status' => TRUE,
    ])->save();
    $this->refreshTestStateAfterRestConfigChange();

    $this->initAuthentication();

    // POST to create a File entity.     $url = Url::fromUri('base:file/upload/media/camelids/field_media_file');
    $url->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS] = [
      // Set the required (and only accepted) content type for the request.       'Content-Type' => 'application/octet-stream',
      // Set the required Content-Disposition header for the file name.       'Content-Disposition' => 'file; filename="drupal rocks 🤘.txt"',
    ];
    
$this->resetAll();
    $this->assertEmpty($user->getPassword());
    $this->assertTrue($user->isBlocked());

    $this->assertMailString('body', 'Your application for an account is', 2);
    $this->assertMailString('body', 'Bob.Arctor has applied for an account', 2);

    // Verify that an authenticated user cannot register a new user, despite     // being granted permission to do so because only anonymous users can     // register themselves, authenticated users with the necessary permissions     // can POST a new user to the "user" REST resource.     $this->initAuthentication();
    $response = $this->registerRequest($this->account->getAccountName());
    $this->assertResourceErrorResponse(403, "Only anonymous users can register a user.", $response);
  }

  /** * Create the request body. * * @param string $name * Name. * @param bool $include_password * Include Password. * @param bool $include_email * Include Email. * * @return array * Return the request body. */
return parent::getExpectedUnauthorizedAccessMessage($method);
  }

  /** * 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.


  /** * Tests PATCHing security-sensitive base fields of the logged in account. */
  public function testPatchDxForSecuritySensitiveBaseFields() {
    // The anonymous user is never allowed to modify itself.     if (!static::$auth) {
      $this->markTestSkipped();
    }

    $this->initAuthentication();
    $this->provisionEntityResource();

    /** @var \Drupal\user\UserInterface $user */
    $user = static::$auth ? $this->account : User::load(0);
    // @todo Remove the array_diff_key() call in https://www.drupal.org/node/2821077.     $original_normalization = array_diff_key($this->serializer->normalize($userstatic::$format)['created' => TRUE, 'changed' => TRUE, 'name' => TRUE]);

    // Since this test must be performed by the user that is being modified,     // we cannot use $this->getUrl().     $url = $user->toUrl()->setOption('query', ['_format' => static::$format]);
    $request_options = [
      
// Write a log message to the DB.     $this->container->get('logger.channel.rest')->notice('Test message');
    // Get the ID of the written message.     $id = Database::getConnection()->select('watchdog', 'w')
      ->fields('w', ['wid'])
      ->condition('type', 'rest')
      ->orderBy('wid', 'DESC')
      ->range(0, 1)
      ->execute()
      ->fetchField();

    $this->initAuthentication();
    $url = Url::fromRoute(
      'rest.dblog.GET',
      ['id' => $id, '_format' => static::$format]
    );
    $request_options = $this->getAuthenticationRequestOptions('GET');

    $response = $this->request('GET', $url$request_options);
    $this->assertResourceErrorResponse(
      403,
      "The 'restful get dblog' permission is required.",
      $response,
      [
protected function getNormalizedPostEntity() {
    // @todo Update in https://www.drupal.org/node/2300677.     return [];
  }

  /** * 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);
  }

}
protected function getExpectedCacheContexts() {
    return [
      'url.site',
      'user.permissions',
    ];
  }

  /** * Tests a GET request for an entity, plus edge cases to ensure good DX. */
  public function testGet() {
    $this->initAuthentication();
    $has_canonical_url = $this->entity->hasLinkTemplate('canonical');

    // The URL and Guzzle request options that will be used in this test. The     // request options will be modified/expanded throughout this test:     // - to first test all mistakes a developer might make, and assert that the     // error responses provide a good DX     // - to eventually result in a well-formed request that succeeds.     $url = $this->getEntityResourceUrl();
    $request_options = [];

    // DX: 404 when resource not provisioned, 403 if canonical route. HTML

  }

  /** * Tests PATCHing a term's path. * * For a negative test, see the similar test coverage for Node. * * @see \Drupal\Tests\rest\Functional\EntityResource\Node\NodeResourceTestBase::testPatchPath() */
  public function testPatchPath() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');

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

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

    // Change term's path alias.

  public function testPostDxWithoutCriticalBaseFields() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('POST');

    $url = $this->getEntityResourcePostUrl()->setOption('query', ['_format' => static::$format]);
    $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'));

    // DX: 422 when missing 'entity_type' field.     $request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity()['entity_type' => TRUE])static::$format);
    

      'status' => TRUE,
    ])->save();

    $this->refreshTestStateAfterRestConfigChange();
  }

  /** * Tests using the file upload POST route. */
  public function testPostFileUpload() {
    $this->initAuthentication();

    $this->provisionResource([static::$format]static::$auth ? [static::$auth] : []['POST']);

    $uri = Url::fromUri('base:' . static::$postUri);

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

    $this->setUpAuthorization('POST');

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