Skip to content

Commit

Permalink
Prevent from throwing an exception when setting default values (#561)
Browse files Browse the repository at this point in the history
- this happens when an expected object has a different type
   i.e. a string.
 - This is prevented by checking the type of the node before
   attemping to set the defaults
  • Loading branch information
josejulio committed Apr 25, 2022
1 parent 99a5389 commit 39cc79b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/main/java/com/networknt/schema/PropertiesValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package com.networknt.schema;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.networknt.schema.walk.DefaultPropertyWalkListenerRunner;
import com.networknt.schema.walk.WalkListenerRunner;
Expand Down Expand Up @@ -114,7 +115,7 @@ private void addToEvaluatedProperties(String propertyPath) {
@Override
public Set<ValidationMessage> walk(JsonNode node, JsonNode rootNode, String at, boolean shouldValidateSchema) {
HashSet<ValidationMessage> validationMessages = new LinkedHashSet<ValidationMessage>();
if (applyDefaultsStrategy.shouldApplyPropertyDefaults()) {
if (applyDefaultsStrategy.shouldApplyPropertyDefaults() && node.getNodeType() == JsonNodeType.OBJECT) {
applyPropertyDefaults((ObjectNode) node);
}
if (shouldValidateSchema) {
Expand Down
30 changes: 30 additions & 0 deletions src/test/java/com/networknt/schema/PropertiesValidatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.networknt.schema;

import com.fasterxml.jackson.databind.JsonNode;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
* Created by josejulio on 25/04/22.
*/
public class PropertiesValidatorTest extends BaseJsonSchemaValidatorTest {

@Test
public void testDoesNotThrowWhenApplyingDefaultPropertiesToNonObjects() throws Exception {
Assertions.assertDoesNotThrow(() -> {
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);

SchemaValidatorsConfig schemaValidatorsConfig = new SchemaValidatorsConfig();
schemaValidatorsConfig.setApplyDefaultsStrategy(new ApplyDefaultsStrategy(
true,
true,
true
));

JsonSchema schema = factory.getSchema("{\"type\":\"object\",\"properties\":{\"foo\":{\"type\":\"object\", \"properties\": {} },\"i-have-default\":{\"type\":\"string\",\"default\":\"foo\"}}}", schemaValidatorsConfig);
JsonNode node = getJsonNodeFromStringContent("{\"foo\": \"bar\"}");
ValidationResult result = schema.walk(node, true);
Assertions.assertEquals(result.getValidationMessages().size(), 1);
});
}
}

0 comments on commit 39cc79b

Please sign in to comment.