1 package com.networknt.schema; 2 3 import com.fasterxml.jackson.databind.JsonNode; 4 import com.fasterxml.jackson.databind.ObjectMapper; 5 import com.networknt.schema.serialization.JsonMapperFactory; 6 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.text.MessageFormat; 10 import java.util.Optional; 11 import java.util.Set; 12 13 import static org.junit.jupiter.api.Assertions.assertTrue; 14 15 /** 16 * Abstract class to use if the data JSON has a declared schema node at root level 17 * 18 * @see Issue769ContainsTest 19 * @author vwuilbea 20 */ 21 public abstract class AbstractJsonSchemaTest { 22 23 private static final String SCHEMA = "$schema"; 24 private static final SpecVersion.VersionFlag DEFAULT_VERSION_FLAG = SpecVersion.VersionFlag.V202012; 25 private static final String ASSERT_MSG_ERROR_CODE = "Validation result should contain {0} error code"; 26 private static final String ASSERT_MSG_TYPE = "Validation result should contain {0} type"; 27 validate(String dataPath)28 protected Set<ValidationMessage> validate(String dataPath) { 29 JsonNode dataNode = getJsonNodeFromPath(dataPath); 30 return getJsonSchemaFromDataNode(dataNode).validate(dataNode); 31 } 32 assertValidatorType(String filename, ValidatorTypeCode validatorTypeCode)33 protected void assertValidatorType(String filename, ValidatorTypeCode validatorTypeCode) { 34 Set<ValidationMessage> validationMessages = validate(getDataTestFolder() + filename); 35 36 assertTrue( 37 validationMessages.stream().anyMatch(vm -> validatorTypeCode.getErrorCode().equals(vm.getCode())), 38 () -> MessageFormat.format(ASSERT_MSG_ERROR_CODE, validatorTypeCode.getErrorCode())); 39 assertTrue( 40 validationMessages.stream().anyMatch(vm -> validatorTypeCode.getValue().equals(vm.getType())), 41 () -> MessageFormat.format(ASSERT_MSG_TYPE, validatorTypeCode.getValue())); 42 } 43 getDataTestFolder()44 protected abstract String getDataTestFolder(); 45 getJsonSchemaFromDataNode(JsonNode dataNode)46 private JsonSchema getJsonSchemaFromDataNode(JsonNode dataNode) { 47 return Optional.ofNullable(dataNode.get(SCHEMA)) 48 .map(JsonNode::textValue) 49 .map(this::getJsonNodeFromPath) 50 .map(this::getJsonSchema) 51 .orElseThrow(() -> new IllegalArgumentException("No schema found on document to test")); 52 } 53 getJsonNodeFromPath(String dataPath)54 private JsonNode getJsonNodeFromPath(String dataPath) { 55 InputStream dataInputStream = getClass().getResourceAsStream(dataPath); 56 ObjectMapper mapper = JsonMapperFactory.getInstance(); 57 try { 58 return mapper.readTree(dataInputStream); 59 } catch(IOException e) { 60 throw new RuntimeException(e); 61 } 62 } 63 getJsonSchema(JsonNode schemaNode)64 private JsonSchema getJsonSchema(JsonNode schemaNode) { 65 return JsonSchemaFactory 66 .getInstance(SpecVersionDetector.detectOptionalVersion(schemaNode, false).orElse(DEFAULT_VERSION_FLAG)) 67 .getSchema(schemaNode); 68 } 69 70 } 71