function ValidKeysConstraintValidatorTest::testValidKeyInference

Same name and namespace in other branches
  1. 10 core/tests/Drupal/KernelTests/Core/TypedData/ValidKeysConstraintValidatorTest.php \Drupal\KernelTests\Core\TypedData\ValidKeysConstraintValidatorTest::testValidKeyInference()

Tests that valid keys can be inferred from the data definition.

File

core/tests/Drupal/KernelTests/Core/TypedData/ValidKeysConstraintValidatorTest.php, line 320

Class

ValidKeysConstraintValidatorTest
Tests the ValidKeys validation constraint.

Namespace

Drupal\KernelTests\Core\TypedData

Code

public function testValidKeyInference() : void {
  // Install the System module and its config so that we can test that the
  // validator infers the allowed keys from a defined schema.
  $this->enableModules([
    'system',
  ]);
  $this->installConfig('system');
  $config = $this->container
    ->get('config.typed')
    ->get('system.site');
  $config->getDataDefinition()
    ->addConstraint('ValidKeys', '<infer>');
  $data = $config->getValue();
  $data['invalid-key'] = "There's a snake in my boots.";
  $config->setValue($data);
  $violations = $config->validate();
  $this->assertCount(1, $violations);
  $this->assertSame("'invalid-key' is not a supported key.", (string) $violations->get(0)
    ->getMessage());
  // Ensure that ValidKeys will freak out if the option is not exactly
  // `<infer>`.
  $config->getDataDefinition()
    ->addConstraint('ValidKeys', 'infer');
  $this->expectExceptionMessage("'infer' is not a valid set of allowed keys.");
  $config->validate();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.