function TermValidationTest::testValidation

Same name in other branches
  1. 9 core/modules/taxonomy/tests/src/Kernel/TermValidationTest.php \Drupal\Tests\taxonomy\Kernel\TermValidationTest::testValidation()
  2. 10 core/modules/taxonomy/tests/src/Kernel/TermValidationTest.php \Drupal\Tests\taxonomy\Kernel\TermValidationTest::testValidation()
  3. 11.x core/modules/taxonomy/tests/src/Kernel/TermValidationTest.php \Drupal\Tests\taxonomy\Kernel\TermValidationTest::testValidation()

Tests the term validation constraints.

File

core/modules/taxonomy/tests/src/Kernel/TermValidationTest.php, line 33

Class

TermValidationTest
Tests term validation constraints.

Namespace

Drupal\Tests\taxonomy\Kernel

Code

public function testValidation() {
    $this->entityTypeManager
        ->getStorage('taxonomy_vocabulary')
        ->create([
        'vid' => 'tags',
        'name' => 'Tags',
    ])
        ->save();
    $term = $this->entityTypeManager
        ->getStorage('taxonomy_term')
        ->create([
        'name' => 'test',
        'vid' => 'tags',
    ]);
    $violations = $term->validate();
    $this->assertCount(0, $violations, 'No violations when validating a default term.');
    $term->set('name', $this->randomString(256));
    $violations = $term->validate();
    $this->assertCount(1, $violations, 'Violation found when name is too long.');
    $this->assertEqual($violations[0]->getPropertyPath(), 'name.0.value');
    $field_label = $term->get('name')
        ->getFieldDefinition()
        ->getLabel();
    $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', [
        '%name' => $field_label,
        '@max' => 255,
    ]));
    $term->set('name', NULL);
    $violations = $term->validate();
    $this->assertCount(1, $violations, 'Violation found when name is NULL.');
    $this->assertEqual($violations[0]->getPropertyPath(), 'name');
    $this->assertEqual($violations[0]->getMessage(), t('This value should not be null.'));
    $term->set('name', 'test');
    $term->set('parent', 9999);
    $violations = $term->validate();
    $this->assertCount(1, $violations, 'Violation found when term parent is invalid.');
    $this->assertEqual($violations[0]->getMessage(), new FormattableMarkup('The referenced entity (%type: %id) does not exist.', [
        '%type' => 'taxonomy_term',
        '%id' => 9999,
    ]));
    $term->set('parent', 0);
    $violations = $term->validate();
    $this->assertCount(0, $violations, 'No violations for parent id 0.');
}

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