3 namespace Drupal\KernelTests\Core\Entity;
5 use Drupal\Core\TypedData\DataDefinition;
6 use Drupal\KernelTests\KernelTestBase;
9 * Tests validation constraints for BundleConstraintValidator.
13 class BundleConstraintValidatorTest extends KernelTestBase {
16 * The typed data manager to use.
18 * @var \Drupal\Core\TypedData\TypedDataManager
22 public static $modules = ['node', 'field', 'text', 'user'];
24 protected function setUp() {
26 $this->installEntitySchema('user');
27 $this->typedData = $this->container->get('typed_data_manager');
31 * Tests bundle constraint validation.
33 public function testValidation() {
34 // Test with multiple values.
35 $this->assertValidation(['foo', 'bar']);
36 // Test with a single string value as well.
37 $this->assertValidation('foo');
41 * Executes the BundleConstraintValidator test for a given bundle.
43 * @param string|array $bundle
44 * Bundle/bundles to use as constraint option.
46 protected function assertValidation($bundle) {
47 // Create a typed data definition with a Bundle constraint.
48 $definition = DataDefinition::create('entity_reference')
49 ->addConstraint('Bundle', $bundle);
51 // Test the validation.
52 $node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'foo']);
54 $typed_data = $this->typedData->create($definition, $node);
55 $violations = $typed_data->validate();
56 $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
58 // Test the validation when an invalid value is passed.
59 $page_node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'baz']);
61 $typed_data = $this->typedData->create($definition, $page_node);
62 $violations = $typed_data->validate();
63 $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.');
65 // Make sure the information provided by a violation is correct.
66 $violation = $violations[0];
67 $this->assertEqual($violation->getMessage(), t('The entity must be of bundle %bundle.', ['%bundle' => implode(', ', (array) $bundle)]), 'The message for invalid value is correct.');
68 $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
69 $this->assertEqual($violation->getInvalidValue(), $page_node, 'The invalid value is set correctly in the violation.');