3 namespace Drupal\KernelTests\Core\Entity;
6 * Tests entity level validation constraints.
10 class EntityTypeConstraintsTest extends EntityKernelTestBase {
15 protected function setUp() {
17 $this->installEntitySchema('entity_test_constraints');
21 * Tests defining entity constraints via entity type annotations and hooks.
23 public function testConstraintDefinition() {
24 // Test reading the annotation. There should be two constraints, the defined
25 // constraint and the automatically added EntityChanged constraint.
26 $entity_type = $this->entityManager->getDefinition('entity_test_constraints');
27 $default_constraints = [
29 'EntityChanged' => NULL,
30 'EntityUntranslatableFields' => NULL,
32 $this->assertEqual($default_constraints, $entity_type->getConstraints());
34 // Enable our test module and test extending constraints.
35 $this->enableModules(['entity_test_constraints']);
36 $this->container->get('module_handler')->resetImplementations();
38 $extra_constraints = ['Test' => []];
39 $this->state->set('entity_test_constraints.build', $extra_constraints);
40 // Re-fetch the entity manager from the new container built after the new
41 // modules were enabled.
42 $this->entityManager = $this->container->get('entity.manager');
43 $this->entityManager->clearCachedDefinitions();
44 $entity_type = $this->entityManager->getDefinition('entity_test_constraints');
45 $this->assertEqual($default_constraints + $extra_constraints, $entity_type->getConstraints());
47 // Test altering constraints.
48 $altered_constraints = ['Test' => ['some_setting' => TRUE]];
49 $this->state->set('entity_test_constraints.alter', $altered_constraints);
50 // Clear the cache in state instance in the Drupal container, so it can pick
51 // up the modified value.
52 \Drupal::state()->resetCache();
53 $this->entityManager->clearCachedDefinitions();
54 $entity_type = $this->entityManager->getDefinition('entity_test_constraints');
55 $this->assertEqual($altered_constraints, $entity_type->getConstraints());
59 * Tests entity constraints are validated.
61 public function testConstraintValidation() {
62 $entity = $this->entityManager->getStorage('entity_test_constraints')->create();
63 $entity->user_id->target_id = 0;
64 $violations = $entity->validate();
65 $this->assertEqual($violations->count(), 0, 'Validation passed.');
67 $entity->changed->value = REQUEST_TIME - 86400;
68 $violations = $entity->validate();
69 $this->assertEqual($violations->count(), 1, 'Validation failed.');
70 $this->assertEqual($violations[0]->getMessage(), t('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.'));