Skip to content

Prevent from throwing an exception when setting default values #561

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
});
}
}