3 namespace Drupal\KernelTests\Core\TypedData;
5 use Drupal\Core\TypedData\DataDefinition;
6 use Drupal\Core\TypedData\MapDataDefinition;
7 use Drupal\KernelTests\KernelTestBase;
10 * Tests ComplexData validation constraint with both valid and invalid values
15 class ComplexDataConstraintValidatorTest extends KernelTestBase {
18 * The typed data manager to use.
20 * @var \Drupal\Core\TypedData\TypedDataManager
24 protected function setUp() {
26 $this->typedData = $this->container->get('typed_data_manager');
30 * Tests the ComplexData validation constraint validator.
32 * For testing a map including a constraint on one of its keys is defined.
34 public function testValidation() {
35 // Create a definition that specifies some ComplexData constraint.
36 $definition = MapDataDefinition::create()
37 ->setPropertyDefinition('key', DataDefinition::create('integer'))
38 ->addConstraint('ComplexData', [
40 'AllowedValues' => [1, 2, 3],
44 // Test the validation.
45 $typed_data = $this->typedData->create($definition, ['key' => 1]);
46 $violations = $typed_data->validate();
47 $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
49 // Test the validation when an invalid value is passed.
50 $typed_data = $this->typedData->create($definition, ['key' => 4]);
51 $violations = $typed_data->validate();
52 $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.');
54 // Make sure the information provided by a violation is correct.
55 $violation = $violations[0];
56 $this->assertEqual($violation->getMessage(), t('The value you selected is not a valid choice.'), 'The message for invalid value is correct.');
57 $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
58 $this->assertEqual($violation->getInvalidValue(), 4, 'The invalid value is set correctly in the violation.');
60 // Test using the constraint with a map without the specified key. This
61 // should be ignored as long as there is no NotNull or NotBlank constraint.
62 $typed_data = $this->typedData->create($definition, ['foo' => 'bar']);
63 $violations = $typed_data->validate();
64 $this->assertEqual($violations->count(), 0, 'Constraint on non-existing key is ignored.');
66 $definition = MapDataDefinition::create()
67 ->setPropertyDefinition('key', DataDefinition::create('integer'))
68 ->addConstraint('ComplexData', [
74 $typed_data = $this->typedData->create($definition, ['foo' => 'bar']);
75 $violations = $typed_data->validate();
76 $this->assertEqual($violations->count(), 1, 'Key is required.');