DevfileSchemaValidator { public void validate(JsonNode contentNode) throws DevfileFormatException { try { List<Problem> validationErrors = new ArrayList<>(); ProblemHandler handler = ProblemHandler.collectingTo(validationErrors); if (!contentNode.hasNonNull("apiVersion")) { throw new DevfileFormatException( "Devfile schema validation failed. Error: The object must have a property whose name is \"apiVersion\"."); } String apiVersion = contentNode.get("apiVersion").asText(); if (!schemasByVersion.containsKey(apiVersion)) { throw new DevfileFormatException( String.format( "Version '%s' of the devfile is not supported. Supported versions are '%s'.", apiVersion, SUPPORTED_VERSIONS)); } JsonSchema schema = schemasByVersion.get(apiVersion); try (JsonReader reader = service.createReader( new StringReader(jsonMapper.writeValueAsString(contentNode)), schema, handler)) { reader.read(); } if (!validationErrors.isEmpty()) { String error = errorMessageComposer.extractMessages(validationErrors, new StringBuilder()); throw new DevfileFormatException( format("Devfile schema validation failed. Error: %s", error)); } } catch (IOException e) { throw new DevfileFormatException("Unable to validate Devfile. Error: " + e.getMessage()); } } @Inject  DevfileSchemaValidator(DevfileSchemaProvider schemaProvider); void validate(JsonNode contentNode);  }
@Test(dataProvider = "validDevfiles") public void shouldNotThrowExceptionOnValidationOfValidDevfile(String resourceFilePath) throws Exception { schemaValidator.validate(yamlMapper.readTree(getResource(resourceFilePath))); }
@Test(dataProvider = "invalidDevfiles") public void shouldThrowExceptionOnValidationOfNonValidDevfile( String resourceFilePath, String expectedMessage) throws Exception { try { schemaValidator.validate(yamlMapper.readTree(getResource(resourceFilePath))); } catch (DevfileFormatException e) { assertEquals( e.getMessage(), format("Devfile schema validation failed. Error: %s", expectedMessage), "DevfileFormatException thrown with message that doesn't match expected message:"); return; } fail("DevfileFormatException expected to be thrown but is was not"); }
@Test public void shouldThrowExceptionWhenDevfileHasUnsupportedApiVersion() throws Exception { try { String devfile = "---\n" + "apiVersion: 111.111\n" + "metadata:\n" + " name: test-invalid-apiversion\n"; schemaValidator.validate(yamlMapper.readTree(devfile)); } catch (DevfileFormatException e) { assertEquals( e.getMessage(), "Version '111.111' of the devfile is not supported. " + "Supported versions are '" + Constants.SUPPORTED_VERSIONS + "'."); return; } fail("DevfileFormatException expected to be thrown but is was not"); }