View source
<?php
namespace Drupal\system\Tests\Validation;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\TypedData\MapDataDefinition;
use Drupal\simpletest\KernelTestBase;
class ComplexDataConstraintValidatorTest extends KernelTestBase {
protected $typedData;
protected function setUp() {
parent::setUp();
$this->typedData = $this->container
->get('typed_data_manager');
}
public function testValidation() {
$definition = MapDataDefinition::create()
->setPropertyDefinition('key', DataDefinition::create('integer'))
->addConstraint('ComplexData', array(
'key' => array(
'AllowedValues' => array(
1,
2,
3,
),
),
));
$typed_data = $this->typedData
->create($definition, array(
'key' => 1,
));
$violations = $typed_data
->validate();
$this
->assertEqual($violations
->count(), 0, 'Validation passed for correct value.');
$typed_data = $this->typedData
->create($definition, array(
'key' => 4,
));
$violations = $typed_data
->validate();
$this
->assertEqual($violations
->count(), 1, 'Validation failed for incorrect value.');
$violation = $violations[0];
$this
->assertEqual($violation
->getMessage(), t('The value you selected is not a valid choice.'), 'The message for invalid value is correct.');
$this
->assertEqual($violation
->getRoot(), $typed_data, 'Violation root is correct.');
$this
->assertEqual($violation
->getInvalidValue(), 4, 'The invalid value is set correctly in the violation.');
$typed_data = $this->typedData
->create($definition, array(
'foo' => 'bar',
));
$violations = $typed_data
->validate();
$this
->assertEqual($violations
->count(), 0, 'Constraint on non-existing key is ignored.');
$definition = MapDataDefinition::create()
->setPropertyDefinition('key', DataDefinition::create('integer'))
->addConstraint('ComplexData', array(
'key' => array(
'NotNull' => array(),
),
));
$typed_data = $this->typedData
->create($definition, array(
'foo' => 'bar',
));
$violations = $typed_data
->validate();
$this
->assertEqual($violations
->count(), 1, 'Key is required.');
}
}