knowledge-8.x-1.x-dev/tests/src/Functional/Rest/KnowledgeResourceTestBase.php
tests/src/Functional/Rest/KnowledgeResourceTestBase.php
<?php
namespace Drupal\Tests\knowledge\Functional\Rest;
use Drupal\Component\Utility\DeprecationHelper;
use Drupal\Core\Cache\Cache;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\EntityTestHelper;
use Drupal\knowledge\Entity\Knowledge;
use Drupal\knowledge\Entity\KnowledgeType;
use Drupal\knowledge\Tests\KnowledgeTestTrait;
use Drupal\user\Entity\User;
use GuzzleHttp\RequestOptions;
/**
* Abstract class from tests rest API.
*/
abstract class KnowledgeResourceTestBase extends EntityResourceTestBase {
use KnowledgeTestTrait;
/**
* {@inheritdoc}
*/
protected static $modules = ['knowledge', 'entity_test', 'node'];
/**
* {@inheritdoc}
*/
protected static $entityTypeId = 'knowledge';
/**
* {@inheritdoc}
*/
protected static $patchProtectedFieldNames = [
'status' => "The 'administer knowledge' permission is required.",
'uid' => "The 'administer knowledge' permission is required.",
'entity_id' => NULL,
'name' => "The 'administer knowledge' permission is required.",
'created' => "The 'administer knowledge' permission is required.",
'changed' => NULL,
'thread' => NULL,
'entity_type' => NULL,
'field_name' => NULL,
];
/**
* The test entity.
*
* @var \Drupal\knowledge\KnowledgeInterface
*/
protected $entity;
/**
* {@inheritdoc}
*/
protected function setUpAuthorization($method) {
switch ($method) {
case 'GET':
$this->grantPermissionsToTestedRole([
'access knowledge',
'view test entity',
]);
break;
case 'POST':
$this->grantPermissionsToTestedRole(['post knowledge']);
break;
case 'PATCH':
// Anonymous users are not ever allowed to edit their own knowledge. To
// be able to test PATCHing knowledge as the anonymous user, the more
// permissive 'administer knowledge' permission must be granted.
// @see \Drupal\knowledge\KnowledgeAccessControlHandler::checkAccess
if (static::$auth) {
$this->grantPermissionsToTestedRole(['edit own knowledge']);
}
else {
$this->grantPermissionsToTestedRole(['administer knowledge']);
}
break;
case 'DELETE':
$this->grantPermissionsToTestedRole(['administer knowledge']);
break;
}
}
/**
* {@inheritdoc}
*/
protected function createEntity() {
// Create a "bar" bundle for the "entity_test" entity type and create.
$bundle = 'bar';
DeprecationHelper::backwardsCompatibleCall(
currentVersion: \Drupal::VERSION,
deprecatedVersion: '11.2.0',
currentCallable: fn() => EntityTestHelper::createBundle($bundle, NULL, 'entity_test'),
deprecatedCallable: fn() => entity_test_create_bundle($bundle, NULL, 'entity_test')
);
// Create a knowledge field on this bundle.
$this->addDefaultKnowledgeField('entity_test', 'bar', 'knowledge');
// Create a "Camelids" test entity that the knowledge will be assigned to.
$linked_entity = EntityTest::create([
'name' => 'Camelids',
'type' => 'bar',
]);
$linked_entity->save();
// Create a "Llama" knowledge.
$knowledge = Knowledge::create([
'knowledge_body' => [
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
],
'entity_id' => $linked_entity->id(),
'entity_type' => 'entity_test',
'field_name' => 'knowledge',
]);
$knowledge->setOwnerId(static::$auth ? $this->account->id() : 0)
->setPublished()
->setCreatedTime(123456789)
->setChangedTime(123456789);
$knowledge->save();
return $knowledge;
}
/**
* {@inheritdoc}
*/
protected function getExpectedNormalizedEntity() {
$author = User::load($this->entity->getOwnerId());
return [
'kid' => [
['value' => 1],
],
'uuid' => [
['value' => $this->entity->uuid()],
],
'langcode' => [
[
'value' => 'en',
],
],
'knowledge_type' => [
[
'target_id' => 'knowledge',
'target_type' => 'knowledge_type',
'target_uuid' => KnowledgeType::load('knowledge')->uuid(),
],
],
'subject' => [
[
'value' => 'Llama',
],
],
'status' => [
[
'value' => TRUE,
],
],
'created' => [
[
'value' => (new \DateTime())->setTimestamp(123456789)->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
'format' => \DateTime::RFC3339,
],
],
'changed' => [
[
'value' => (new \DateTime())->setTimestamp((int) $this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339),
'format' => \DateTime::RFC3339,
],
],
'default_langcode' => [
[
'value' => TRUE,
],
],
'uid' => [
[
'target_id' => (int) $author->id(),
'target_type' => 'user',
'target_uuid' => $author->uuid(),
'url' => base_path() . 'user/' . $author->id(),
],
],
'entity_type' => [
[
'value' => 'entity_test',
],
],
'entity_id' => [
[
'target_id' => 1,
'target_type' => 'entity_test',
'target_uuid' => EntityTest::load(1)->uuid(),
'url' => base_path() . 'entity_test/1',
],
],
'field_name' => [
[
'value' => 'knowledge',
],
],
'name' => [],
'knowledge_body' => [
[
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
'format' => 'plain_text',
'processed' => '<p>The name "llama" was adopted by European settlers from native Peruvians.</p>' . "\n",
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPostEntity() {
return [
'knowledge_type' => [
[
'target_id' => 'knowledge',
],
],
'entity_type' => [
[
'value' => 'entity_test',
],
],
'entity_id' => [
[
'target_id' => (int) EntityTest::load(1)->id(),
],
],
'field_name' => [
[
'value' => 'knowledge',
],
],
'subject' => [
[
'value' => 'Dramallama',
],
],
'knowledge_body' => [
[
'value' => 'Llamas are awesome.',
'format' => 'plain_text',
],
],
];
}
/**
* {@inheritdoc}
*/
protected function getNormalizedPatchEntity() {
return array_diff_key($this->getNormalizedPostEntity(), [
'entity_type' => TRUE,
'entity_id' => TRUE,
'field_name' => TRUE,
]);
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheTags() {
return Cache::mergeTags(parent::getExpectedCacheTags(), ['config:filter.format.plain_text']);
}
/**
* {@inheritdoc}
*/
protected function getExpectedCacheContexts() {
return Cache::mergeContexts(['languages:language_interface', 'theme'], parent::getExpectedCacheContexts());
}
/**
* Tests POSTing a knowledge without critical base fields.
*
* Tests with the most minimal normalization possible: the one returned by
* ::getNormalizedPostEntity().
*
* But Knowledge entities have some very special edge cases:
* - base fields that are not marked as required in
* \Drupal\knowledge\Entity\Knowledge::baseFieldDefinitions() yet in fact
* are required.
* - base fields that are marked as required, but yet can still result in
* validation errors other than "missing required field".
*/
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);
$response = $this->request('POST', $url, $request_options);
$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_type: This value should not be null.\n", $response);
// DX: 422 when missing 'entity_id' field.
$request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['entity_id' => TRUE]), static::$format);
$response = $this->request('POST', $url, $request_options);
$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_id: This value should not be null.\n", $response);
// DX: 422 when missing 'field_name' field.
$request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['field_name' => TRUE]), static::$format);
$response = $this->request('POST', $url, $request_options);
$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nfield_name: This value should not be null.\n", $response);
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedAccessMessage($method) {
switch ($method) {
case 'GET':
return "The 'access knowledge' permission is required and the knowledge must be published.";
case 'POST':
return "The 'post knowledge' permission is required.";
case 'PATCH':
return "The 'edit own knowledge' permission is required, the user must be the knowledge author, and the knowledge must be published.";
case 'DELETE':
default:
// \Drupal\knowledge\KnowledgeAccessControlHandler::checkAccess() does
// not specify a reason for not allowing a knowledge to be deleted.
return '';
}
}
/**
* Tests POSTing a knowledge with and without 'skip knowledge approval'.
*/
public function testPostSkipKnowledgeApproval() {
$this->initAuthentication();
$this->provisionEntityResource();
$this->setUpAuthorization('POST');
// Create request.
$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);
/** @var \Drupal\knowledge\KnowledgeInterface $unserialized */
$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 knowledge approval.
$this->grantPermissionsToTestedRole(['skip knowledge approval']);
// Status should be TRUE when posting as anonymous
// and skip knowledge approval.
$response = $this->request('POST', $url, $request_options);
/** @var \Drupal\knowledge\KnowledgeInterface $unserialized */
$unserialized = $this->serializer->deserialize((string) $response->getBody(), get_class($this->entity), static::$format);
$this->assertResourceResponse(201, FALSE, $response);
$this->assertTrue($unserialized->isPublished());
}
/**
* {@inheritdoc}
*/
protected function getExpectedUnauthorizedEntityAccessCacheability($is_authenticated) {
// @see \Drupal\knowledge\KnowledgeAccessControlHandler::checkAccess()
return parent::getExpectedUnauthorizedEntityAccessCacheability($is_authenticated)
->addCacheTags(['knowledge:1']);
}
}
