EntityTypeConstraintValidatorTest.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Drupal\KernelTests\Core\Entity;
  3. use Drupal\Core\TypedData\DataDefinition;
  4. /**
  5. * Tests validation constraints for EntityTypeConstraintValidator.
  6. *
  7. * @group Entity
  8. */
  9. class EntityTypeConstraintValidatorTest extends EntityKernelTestBase {
  10. /**
  11. * The typed data manager to use.
  12. *
  13. * @var \Drupal\Core\TypedData\TypedDataManager
  14. */
  15. protected $typedData;
  16. public static $modules = ['node', 'field', 'user'];
  17. protected function setUp() {
  18. parent::setUp();
  19. $this->typedData = $this->container->get('typed_data_manager');
  20. }
  21. /**
  22. * Tests the EntityTypeConstraintValidator.
  23. */
  24. public function testValidation() {
  25. // Create a typed data definition with an EntityType constraint.
  26. $entity_type = 'node';
  27. $definition = DataDefinition::create('entity_reference')
  28. ->setConstraints([
  29. 'EntityType' => $entity_type,
  30. ]
  31. );
  32. // Test the validation.
  33. $node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'page']);
  34. $typed_data = $this->typedData->create($definition, $node);
  35. $violations = $typed_data->validate();
  36. $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
  37. // Test the validation when an invalid value (in this case a user entity)
  38. // is passed.
  39. $account = $this->createUser();
  40. $typed_data = $this->typedData->create($definition, $account);
  41. $violations = $typed_data->validate();
  42. $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.');
  43. // Make sure the information provided by a violation is correct.
  44. $violation = $violations[0];
  45. $this->assertEqual($violation->getMessage(), t('The entity must be of type %type.', ['%type' => $entity_type]), 'The message for invalid value is correct.');
  46. $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
  47. $this->assertEqual($violation->getInvalidValue(), $account, 'The invalid value is set correctly in the violation.');
  48. }
  49. }