Upgraded drupal core with security updates
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Entity / BundleConstraintValidatorTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Entity;
4
5 use Drupal\Core\TypedData\DataDefinition;
6 use Drupal\KernelTests\KernelTestBase;
7
8 /**
9  * Tests validation constraints for BundleConstraintValidator.
10  *
11  * @group Entity
12  */
13 class BundleConstraintValidatorTest extends KernelTestBase {
14
15   /**
16    * The typed data manager to use.
17    *
18    * @var \Drupal\Core\TypedData\TypedDataManager
19    */
20   protected $typedData;
21
22   public static $modules = ['node', 'field', 'text', 'user'];
23
24   protected function setUp() {
25     parent::setUp();
26     $this->installEntitySchema('user');
27     $this->typedData = $this->container->get('typed_data_manager');
28   }
29
30   /**
31    * Tests bundle constraint validation.
32    */
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');
38   }
39
40   /**
41    * Executes the BundleConstraintValidator test for a given bundle.
42    *
43    * @param string|array $bundle
44    *   Bundle/bundles to use as constraint option.
45    */
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);
50
51     // Test the validation.
52     $node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'foo']);
53
54     $typed_data = $this->typedData->create($definition, $node);
55     $violations = $typed_data->validate();
56     $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
57
58     // Test the validation when an invalid value is passed.
59     $page_node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'baz']);
60
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.');
64
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.');
70   }
71
72 }