protected function ValidateSchemaTest::validateSchemaAsJsonSchema in Schemata 8
Confirm a schema is inherently valid as a JSON Schema.
@todo how do you handle tests that should stop processing on a failure.
Parameters
string $format: The described format.
string $entity_type_id: Then entity type.
string|null $bundle_id: The bundle name or NULL.
1 call to ValidateSchemaTest::validateSchemaAsJsonSchema()
- ValidateSchemaTest::testSchemataAreValidJsonSchema in tests/
src/ Functional/ ValidateSchemaTest.php - Test the generated schemas are valid JSON Schema.
File
- tests/
src/ Functional/ ValidateSchemaTest.php, line 58
Class
- ValidateSchemaTest
- Tests that generated JSON Schemas are valid as JSON Schema.
Namespace
Drupal\Tests\schemata\FunctionalCode
protected function validateSchemaAsJsonSchema($format, $entity_type_id, $bundle_id = NULL) {
$json = $this
->getRawSchemaByOptions($format, $entity_type_id, $bundle_id);
$this
->assertSession()
->statusCodeEquals(200);
// Requesting config entity schema gets a 200 response but no content.
// @todo return an error on requesting config schema.
$this
->assertTrue(!empty($json), 'Schema request should provide response content instead of a NULL value.');
try {
$data = json_decode($json, FALSE, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this
->assertTrue(FALSE, "Could not decode JSON from schema response. Error: " . $e
->getMessage());
}
$this
->assertNotEmpty($data->{'$schema'}, 'JSON Schema should include a $schema reference to a defining schema.');
// Prepare the schema for validation.
// By definition of the JSON Schema spec, schemas use a top-level '$schema'
// key to identify the schema specification with which they conform.
$schema = $this
->getDereferencedSchema($data->{'$schema'});
$this
->assertTrue(!empty($schema), 'The schema specification must be retrieved and dereferenced for use.');
// Validate our schema is a correct schema.
$validator = new Validator($data, $schema);
if ($validator
->fails()) {
$bundle_label = empty($bundle_id) ? 'no-bundle' : $bundle_id;
$message = "Schema ({$entity_type_id}:{$bundle_label}) failed validation for {$format}:\n";
$errors = $validator
->errors();
$message .= json_encode($errors, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$this
->assertTrue(FALSE, $message);
}
// Now that the schema has validated correctly, let's confirm an invalid
// schema will fail validation.
$data->properties = '';
$validator = new Validator($data, $schema);
if (!$validator
->fails()) {
$bundle_label = empty($bundle_id) ? 'no-bundle' : $bundle_id;
$message = "Schema ({$entity_type_id}:{$bundle_label}) should fail validation if it is wrong.\n";
$this
->assertTrue(FALSE, $message);
}
}