clean install

This commit is contained in:
2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 changed files with 3555714 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
name: Consumers Test
type: module
description: 'Test module for consumers automated testing purposes.'
package: Testing
dependencies:
- consumers:consumers
- jsonapi:jsonapi
# Information added by Drupal.org packaging script on 2024-07-23
version: '8.x-1.19'
project: 'consumers'
datestamp: 1721753032

View File

@@ -0,0 +1,26 @@
<?php
/**
* @file
* Hooks for the consumers_test module.
*/
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
define('CONSUMERS_TEST_NODE_TYPE', 'test_content_type_name');
/**
* Implements hook_entity_base_field_info().
*/
function consumers_test_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() === 'node') {
$fields['consumer_client_id'] = BaseFieldDefinition::create('string')
->setLabel(t('Consumer client id'))
->setDescription(t('The client id of the consumer for test purposes.'))
->setComputed(TRUE)
->setClass('\Drupal\consumers_test\ConsumerClientIDTestField');
}
return $fields;
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Drupal\consumers_test;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
/**
* Test computed field for client id.
*/
class ConsumerClientIDTestField extends FieldItemList {
use ComputedItemListTrait;
/**
* {@inheritdoc}
*/
protected function computeValue() {
$value = '';
$node = $this->getEntity();
$consumer = \Drupal::service('consumer.negotiator')->negotiateFromRequest();
if ($node->bundle() === CONSUMERS_TEST_NODE_TYPE && $consumer) {
$value = $consumer->getClientId();
}
$this->list[0] = $this->createItem(0, $value);
}
}

View File

@@ -0,0 +1,151 @@
<?php
namespace Drupal\Tests\consumers\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\consumers\Entity\Consumer;
use Drupal\consumers\MissingConsumer;
use Drupal\Tests\jsonapi\Functional\JsonApiFunctionalTestBase;
/**
* Tests the cacheability of the consumer client id field.
*
* @group consumers
*/
class CacheabilityTest extends JsonApiFunctionalTestBase {
/**
* The required modules to install.
*
* @var array
*/
protected static $modules = [
'consumers',
'consumers_test',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The content type for testing.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $contentType;
/**
* Test node.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* Test consumer.
*
* @var \Drupal\consumers\Entity\Consumer
*/
protected $consumer;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->contentType = $this->drupalCreateContentType([
'type' => CONSUMERS_TEST_NODE_TYPE,
]);
$this->node = $this->createNode([
'type' => CONSUMERS_TEST_NODE_TYPE,
]);
$this->consumer = Consumer::create([
'client_id' => $this->randomMachineName(),
'label' => $this->randomString(),
]);
$this->consumer->save();
drupal_flush_all_caches();
}
/**
* Check client id cacheability depending on provided consumer.
*/
public function testClientIdCacheability() {
$path = sprintf(
'/jsonapi/node/%s/%s',
$this->contentType->id(),
$this->node->uuid()
);
$query = [
'consumerId' => $this->consumer->getClientId(),
];
// Pass test consumer and make sure its client id is returned.
$output = Json::decode($this->drupalGet($path, ['query' => $query]));
$this->assertArrayHasKey('consumer_client_id', $output['data']['attributes']);
$this->assertEquals($this->consumer->getClientId(), $output['data']['attributes']['consumer_client_id']);
// Check if test consumer result was not cached and default returned
// when no consumer passed.
$output = Json::decode($this->drupalGet($path));
$this->assertArrayHasKey('consumer_client_id', $output['data']['attributes']);
$this->assertEquals('default_consumer', $output['data']['attributes']['consumer_client_id']);
}
/**
* Verify the site still loads if there are no consumer entities.
*
* @covers \Drupal\consumers\EventSubscriber\ConsumerVaryEventSubscriber::onRespond
*/
public function testNoConsumerEntities() {
// Load, and then delete, all consumer entities.
$consumers = Consumer::loadMultiple();
foreach ($consumers as $consumer) {
$consumer->delete();
}
$this->assertEmpty(Consumer::loadMultiple());
// Assert there is no exception.
$this->drupalGet('<front>');
$this->assertSession()->statusCodeEquals(200);
}
/**
* Verify the site still loads if there are no default consumer entities.
*
* @covers \Drupal\consumers\EventSubscriber\ConsumerVaryEventSubscriber::onRespond
*/
public function testNoDefaultConsumer() {
// Load, and then delete, all consumer entities.
$consumers = Consumer::loadMultiple();
foreach ($consumers as $consumer) {
$consumer->delete();
}
$this->assertEmpty(Consumer::loadMultiple());
// Create a single consumer, but make it no the default.
$consumer = Consumer::create([
'client_id' => $this->randomMachineName(),
'label' => $this->randomString(),
'is_default' => FALSE,
]);
$consumer->save();
// Verify there is no default consumer by trying to negotiate one from the
// request, which has no consumer_id in the headers so tries to load the
// default and then throws an exception.
/** @var \Drupal\consumers\Negotiator $negotiator */
$negotiator = $this->container->get('consumer.negotiator');
$this->expectException(MissingConsumer::class);
$this->expectExceptionMessage('Unable to find the default consumer.');
$negotiator->negotiateFromRequest();
// Verify the above exception is handled properly in
// \Drupal\consumers\EventSubscriber\ConsumerVaryEventSubscriber::onRespond
// when trying to load any page.
$this->drupalGet('<front>');
$this->assertSession()->statusCodeEquals(200);
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace Drupal\Tests\consumers\Kernel;
use Drupal\consumers\Entity\Consumer;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Logger\LoggerChannelFactory;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Symfony\Component\ErrorHandler\BufferingLogger;
/**
* Tests the exception handling in the Consumer entity.
*
* @group consumers
*/
class ConsumerTest extends KernelTestBase {
use UserCreationTrait;
/**
* The consumer entity storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected \Drupal\Core\Entity\EntityStorageInterface $consumerStorage;
/**
* {@inheritdoc}
*/
protected static $modules = [
'system',
'user',
'image',
'file',
'consumers',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Install the required entity schema.
$this->installEntitySchema('consumer');
$this->installEntitySchema('user');
$this->installEntitySchema('file');
// Get the consumer entity storage.
$this->consumerStorage = $this->container->get('entity_type.manager')->getStorage('consumer');
}
/**
* Tests exception handling in preSave method.
*
* @covers \Drupal\consumers\Entity\Consumer::preSave
*/
public function testPreSaveExceptionHandling() {
$admin_user = $this->setUpCurrentUser([], [], TRUE);
$restricted_user = $this->createUser();
// Create a Consumer entity.
$consumer = Consumer::create([
'label' => 'Test Consumer',
'client_id' => 'test_client_id',
'is_default' => TRUE,
]);
$consumer->setOwner($admin_user);
$consumer->save();
// Create a Consumer entity.
$consumer2 = Consumer::create([
'label' => 'Test Consumer',
'client_id' => 'test_client_id',
'is_default' => FALSE,
]);
$consumer->setOwner($admin_user);
$consumer2->save();
// Mock the logger service.
$logger = new BufferingLogger();
$logger_factory = $this->createMock(LoggerChannelFactory::class);
$logger_factory->expects($this->once())
->method('get')
->with('consumers')
->willReturn($logger);
$this->container->set('logger.factory', $logger_factory);
// As a non-authorized user, update the is_default flag to FALSE and try to
// save the consumer again. This should trigger an error in the
// removeDefaultConsumerFlags() method, and revert the is_default flag to
// FALSE.
$this->setCurrentUser($restricted_user);
$consumer2->set('is_default', TRUE);
$this->assertEquals(1, $consumer2->get('is_default')->value);
$consumer2->save();
// Expect the logger to log the exception.
$log_message = $logger->cleanLogs()[0];
$this->assertInstanceOf(AccessException::class, $log_message[2]['exception']);
$this->assertStringContainsString('Unable to change the current default consumer. Permission denied.', $log_message[2]['@message']);
// Reload the updated consumer.
$saved_consumer = $this->consumerStorage->load($consumer2->id());
// Verify that is_default is set to FALSE.
$this->assertEquals(0, $saved_consumer->get('is_default')->value);
$this->setCurrentUser($admin_user);
$saved_consumer->set('is_default', TRUE);
$saved_consumer->save();
// Reload the updated consumer.
$saved_consumer = $this->consumerStorage->load($saved_consumer->id());
// Verify that is_default is set to TRUE.
$this->assertEquals(1, $saved_consumer->get('is_default')->value);
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace Drupal\Tests\consumers\Kernel;
use Drupal\consumers\Entity\Consumer;
use Drupal\consumers\Entity\ConsumerInterface;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
/**
* The negotiator test.
*
* @group consumers
*/
class NegotiatorTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'consumers',
'user',
'file',
'image',
'system',
];
/**
* The consumer.
*
* @var \Drupal\consumers\Entity\ConsumerInterface
*/
protected $consumer;
/**
* The default consumer.
*
* @var \Drupal\consumers\Entity\ConsumerInterface
*/
protected $defaultConsumer;
/**
* The negotiator service.
*
* @var \Drupal\consumers\Negotiator
*/
protected $negotiator;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('user');
$this->installEntitySchema('consumer');
$this->installEntitySchema('file');
$this->installConfig(['user']);
$this->negotiator = $this->container->get('consumer.negotiator');
$this->consumer = Consumer::create([
'label' => 'test',
'client_id' => 'test_consumer_id',
]);
$this->consumer->save();
$this->defaultConsumer = Consumer::create([
'label' => 'default',
'client_id' => 'default',
'is_default' => TRUE,
]);
$this->defaultConsumer->save();
}
/**
* Test negotiation from request with header.
*/
public function testNegotiateFromRequestWithHeader(): void {
$request = Request::create('/');
$request->headers->set('X-Consumer-ID', $this->consumer->getClientId());
$consumer = $this->negotiator->negotiateFromRequest($request);
$this->assertInstanceOf(ConsumerInterface::class, $consumer);
$this->assertEquals($this->consumer->getClientId(), $consumer->getClientId());
$this->assertEquals($this->consumer->getClientId(), $request->attributes->get('consumer_id'));
// If consumer doesn't exist, expected is to fallback on default consumer.
$request->headers->set('X-Consumer-ID', 'unknown');
$consumer = $this->negotiator->negotiateFromRequest($request);
$this->assertInstanceOf(ConsumerInterface::class, $consumer);
$this->assertEquals($this->defaultConsumer->getClientId(), $consumer->getClientId());
$this->assertEquals($this->defaultConsumer->getClientId(), $request->attributes->get('consumer_id'));
}
/**
* Test negotiation from request with query string parameter.
*/
public function testNegotiateFromRequestWithQuery(): void {
$request = Request::create('/', 'GET', [
'consumerId' => $this->consumer->getClientId(),
]);
$consumer = $this->negotiator->negotiateFromRequest($request);
$this->assertInstanceOf(ConsumerInterface::class, $consumer);
$this->assertEquals($this->consumer->getClientId(), $consumer->getClientId());
$this->assertEquals($this->consumer->getClientId(), $request->attributes->get('consumer_id'));
// If consumer doesn't exist, expected is to fallback on default consumer.
$request = Request::create('/', 'GET', [
'consumerId' => 'unknown',
]);
$consumer = $this->negotiator->negotiateFromRequest($request);
$this->assertInstanceOf(ConsumerInterface::class, $consumer);
$this->assertEquals($this->defaultConsumer->getClientId(), $consumer->getClientId());
$this->assertEquals($this->defaultConsumer->getClientId(), $request->attributes->get('consumer_id'));
}
}