EntityTypeConstraintsTest.php in Drupal 9
File
core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php
View source
<?php
namespace Drupal\KernelTests\Core\Entity;
class EntityTypeConstraintsTest extends EntityKernelTestBase {
protected function setUp() : void {
parent::setUp();
$this
->installEntitySchema('entity_test_constraints');
}
public function testConstraintDefinition() {
$entity_type = $this->entityTypeManager
->getDefinition('entity_test_constraints');
$default_constraints = [
'NotNull' => [],
'EntityChanged' => NULL,
'EntityUntranslatableFields' => NULL,
];
$this
->assertEquals($default_constraints, $entity_type
->getConstraints());
$this
->enableModules([
'entity_test_constraints',
]);
$this->container
->get('module_handler')
->resetImplementations();
$extra_constraints = [
'Test' => [],
];
$this->state
->set('entity_test_constraints.build', $extra_constraints);
$this->entityTypeManager = $this->container
->get('entity_type.manager');
$this->entityTypeManager
->clearCachedDefinitions();
$entity_type = $this->entityTypeManager
->getDefinition('entity_test_constraints');
$this
->assertEquals($default_constraints + $extra_constraints, $entity_type
->getConstraints());
$altered_constraints = [
'Test' => [
'some_setting' => TRUE,
],
];
$this->state
->set('entity_test_constraints.alter', $altered_constraints);
\Drupal::state()
->resetCache();
$this->entityTypeManager
->clearCachedDefinitions();
$entity_type = $this->entityTypeManager
->getDefinition('entity_test_constraints');
$this
->assertEquals($altered_constraints, $entity_type
->getConstraints());
}
public function testConstraintValidation() {
$entity = $this->entityTypeManager
->getStorage('entity_test_constraints')
->create();
$entity->user_id->target_id = 0;
$violations = $entity
->validate();
$this
->assertEquals(0, $violations
->count(), 'Validation passed.');
$entity
->save();
$entity->changed->value = REQUEST_TIME - 86400;
$violations = $entity
->validate();
$this
->assertEquals(1, $violations
->count(), 'Validation failed.');
$this
->assertEquals('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.', $violations[0]
->getMessage());
}
}