function NodeValidationTest::testValidation

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

Tests the node validation constraints.

File

core/modules/node/tests/src/Kernel/NodeValidationTest.php, line 37

Class

NodeValidationTest
Tests node validation constraints.

Namespace

Drupal\Tests\node\Kernel

Code

public function testValidation() {
    $this->createUser();
    $node = Node::create([
        'type' => 'page',
        'title' => 'test',
        'uid' => 1,
    ]);
    $violations = $node->validate();
    $this->assertCount(0, $violations, 'No violations when validating a default node.');
    $node->set('title', $this->randomString(256));
    $violations = $node->validate();
    $this->assertCount(1, $violations, 'Violation found when title is too long.');
    $this->assertEquals('title.0.value', $violations[0]->getPropertyPath());
    $this->assertEquals('<em class="placeholder">Title</em>: may not be longer than 255 characters.', $violations[0]->getMessage());
    $node->set('title', NULL);
    $violations = $node->validate();
    $this->assertCount(1, $violations, 'Violation found when title is not set.');
    $this->assertEquals('title', $violations[0]->getPropertyPath());
    $this->assertEquals('This value should not be null.', $violations[0]->getMessage());
    $node->set('title', '');
    $violations = $node->validate();
    $this->assertCount(1, $violations, 'Violation found when title is set to an empty string.');
    $this->assertEquals('title', $violations[0]->getPropertyPath());
    // Make the title valid again.
    $node->set('title', $this->randomString());
    // Save the node so that it gets an ID and a changed date.
    $node->save();
    // Set the changed date to something in the far past.
    $node->set('changed', 433918800);
    $violations = $node->validate();
    $this->assertCount(1, $violations, 'Violation found when changed date is before the last changed date.');
    $this->assertEquals('', $violations[0]->getPropertyPath());
    $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());
}

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