function EntityTypeConstraintsTest::testConstraintDefinition

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintsTest::testConstraintDefinition()
  2. 8.9.x core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintsTest::testConstraintDefinition()
  3. 10 core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php \Drupal\KernelTests\Core\Entity\EntityTypeConstraintsTest::testConstraintDefinition()

Tests defining entity constraints via entity type annotations and hooks.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityTypeConstraintsTest.php, line 25

Class

EntityTypeConstraintsTest
Tests entity level validation constraints.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testConstraintDefinition() : void {
    // Test reading the annotation. There should be two constraints, the defined
    // constraint and the automatically added EntityChanged constraint.
    $entity_type = $this->entityTypeManager
        ->getDefinition('entity_test_constraints');
    $default_constraints = [
        'NotNull' => [],
        'EntityChanged' => NULL,
        'EntityUntranslatableFields' => NULL,
    ];
    $this->assertEquals($default_constraints, $entity_type->getConstraints());
    // Enable our test module and test extending constraints.
    $this->enableModules([
        'entity_test_constraints',
    ]);
    $this->container
        ->get('module_handler')
        ->resetImplementations();
    $extra_constraints = [
        'Test' => [],
    ];
    $this->state
        ->set('entity_test_constraints.build', $extra_constraints);
    // Re-fetch the entity type manager from the new container built after the
    // new modules were enabled.
    $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());
    // Test altering constraints.
    $altered_constraints = [
        'Test' => [
            'some_setting' => TRUE,
        ],
    ];
    $this->state
        ->set('entity_test_constraints.alter', $altered_constraints);
    // Clear the cache in state instance in the Drupal container, so it can pick
    // up the modified value.
    \Drupal::state()->resetCache();
    $this->entityTypeManager
        ->clearCachedDefinitions();
    $entity_type = $this->entityTypeManager
        ->getDefinition('entity_test_constraints');
    $this->assertEquals($altered_constraints, $entity_type->getConstraints());
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.