function UniqueValuesConstraintValidatorTest::testValidation

Same name in other branches
  1. 10 core/tests/Drupal/KernelTests/Core/Validation/UniqueValuesConstraintValidatorTest.php \Drupal\KernelTests\Core\Validation\UniqueValuesConstraintValidatorTest::testValidation()

Tests the UniqueField validation constraint validator.

Case 1. Try to create another entity with existing value for unique field.

@covers ::validate

Throws

\Drupal\Core\Entity\EntityStorageException

File

core/tests/Drupal/KernelTests/Core/Validation/UniqueValuesConstraintValidatorTest.php, line 50

Class

UniqueValuesConstraintValidatorTest
Tests the unique field value validation constraint.

Namespace

Drupal\KernelTests\Core\Validation

Code

public function testValidation() : void {
    // Create entity with two values for the testing field.
    $definition = [
        'id' => (int) rand(0, getrandmax()),
        'user_id' => 0,
        'field_test_text' => [
            'text1',
            'text2',
        ],
    ];
    $entity = EntityTestUniqueConstraint::create($definition);
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    $entity->save();
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    // Create another entity with two values for the testing field.
    $definition = [
        'id' => (int) rand(0, getrandmax()),
        'user_id' => 0,
        'field_test_text' => [
            'text3',
            'text4',
        ],
    ];
    $entity = EntityTestUniqueConstraint::create($definition);
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    $entity->save();
    $violations = $entity->validate();
    $this->assertCount(0, $violations);
    // Add existing value.
    $value = 'text1';
    $entity->get('field_test_text')
        ->appendItem($value);
    $violations = $entity->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('field_test_text.2', $violations[0]->getPropertyPath());
    $this->assertEquals(sprintf('A unique field entity with unique_field_test %s already exists.', $value), $violations[0]->getMessage());
    // Create another entity with two values, but one value is existing.
    $definition = [
        'id' => (int) rand(0, getrandmax()),
        'user_id' => 0,
        'field_test_text' => [
            'text5',
            'text1',
        ],
    ];
    $entity = EntityTestUniqueConstraint::create($definition);
    $violations = $entity->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('field_test_text.1', $violations[0]->getPropertyPath());
    $this->assertEquals(sprintf('A unique field entity with unique_field_test %s already exists.', $definition['field_test_text'][1]), $violations[0]->getMessage());
}

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