Skip to content
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

Fix walk for if validator with validation #1010

Merged
merged 1 commit into from
Apr 4, 2024
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
35 changes: 24 additions & 11 deletions src/main/java/com/networknt/schema/IfValidator.java
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,33 @@ public void preloadJsonSchema() {

@Override
public Set<ValidationMessage> walk(ExecutionContext executionContext, JsonNode node, JsonNode rootNode, JsonNodePath instanceLocation, boolean shouldValidateSchema) {
if (shouldValidateSchema) {
return validate(executionContext, node, rootNode, instanceLocation);
}
boolean checkCondition = node != null && shouldValidateSchema;
boolean ifConditionPassed = false;

if (null != this.ifSchema) {
this.ifSchema.walk(executionContext, node, rootNode, instanceLocation, false);
}
if (null != this.thenSchema) {
this.thenSchema.walk(executionContext, node, rootNode, instanceLocation, false);
// Save flag as nested schema evaluation shouldn't trigger fail fast
boolean failFast = executionContext.isFailFast();
try {
executionContext.setFailFast(false);
ifConditionPassed = this.ifSchema.walk(executionContext, node, rootNode, instanceLocation, shouldValidateSchema).isEmpty();
} finally {
// Restore flag
executionContext.setFailFast(failFast);
}
if (null != this.elseSchema) {
this.elseSchema.walk(executionContext, node, rootNode, instanceLocation, false);
if (!checkCondition) {
if (this.thenSchema != null) {
this.thenSchema.walk(executionContext, node, rootNode, instanceLocation, shouldValidateSchema);
}
if (this.elseSchema != null) {
this.elseSchema.walk(executionContext, node, rootNode, instanceLocation, shouldValidateSchema);
}
} else {
if (this.thenSchema != null && ifConditionPassed) {
return this.thenSchema.walk(executionContext, node, rootNode, instanceLocation, shouldValidateSchema);
}
else if (this.elseSchema != null && !ifConditionPassed) {
return this.elseSchema.walk(executionContext, node, rootNode, instanceLocation, shouldValidateSchema);
}
}

return Collections.emptySet();
}

Expand Down
209 changes: 209 additions & 0 deletions src/test/java/com/networknt/schema/IfValidatorTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
/*
* Copyright (c) 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.junit.jupiter.api.Test;

import com.networknt.schema.SpecVersion.VersionFlag;
import com.networknt.schema.walk.JsonSchemaWalkListener;
import com.networknt.schema.walk.WalkEvent;
import com.networknt.schema.walk.WalkFlow;

/**
* Test for IfValidator.
*/
class IfValidatorTest {

@Test
void walkValidateThen() {
String schemaData = "{\r\n"
+ " \"if\": {\r\n"
+ " \"const\": \"false\"\r\n"
+ " },\r\n"
+ " \"then\": {\r\n"
+ " \"type\": \"object\"\r\n"
+ " },\r\n"
+ " \"else\": {\r\n"
+ " \"type\": \"number\"\r\n"
+ " }\r\n"
+ "}";
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
config.setPathType(PathType.JSON_POINTER);
config.addKeywordWalkListener(ValidatorTypeCode.TYPE.getValue(), new JsonSchemaWalkListener() {

@Override
public WalkFlow onWalkStart(WalkEvent walkEvent) {
return WalkFlow.CONTINUE;
}

@Override
public void onWalkEnd(WalkEvent walkEvent, Set<ValidationMessage> validationMessages) {
@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) walkEvent.getExecutionContext()
.getCollectorContext()
.getCollectorMap()
.computeIfAbsent("types", key -> new ArrayList<JsonNodePath>());
types.add(walkEvent);
}
});
JsonSchema schema = factory.getSchema(schemaData, config);
ValidationResult result = schema.walk("\"false\"", InputFormat.JSON, true);
assertFalse(result.getValidationMessages().isEmpty());

@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) result.getExecutionContext().getCollectorContext().get("types");
assertEquals(1, types.size());
assertEquals("", types.get(0).getInstanceLocation().toString());
assertEquals("/then", types.get(0).getSchema().getEvaluationPath().toString());
}

@Test
void walkValidateElse() {
String schemaData = "{\r\n"
+ " \"if\": {\r\n"
+ " \"const\": \"false\"\r\n"
+ " },\r\n"
+ " \"then\": {\r\n"
+ " \"type\": \"object\"\r\n"
+ " },\r\n"
+ " \"else\": {\r\n"
+ " \"type\": \"number\"\r\n"
+ " }\r\n"
+ "}";
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
config.setPathType(PathType.JSON_POINTER);
config.addKeywordWalkListener(ValidatorTypeCode.TYPE.getValue(), new JsonSchemaWalkListener() {

@Override
public WalkFlow onWalkStart(WalkEvent walkEvent) {
return WalkFlow.CONTINUE;
}

@Override
public void onWalkEnd(WalkEvent walkEvent, Set<ValidationMessage> validationMessages) {
@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) walkEvent.getExecutionContext()
.getCollectorContext()
.getCollectorMap()
.computeIfAbsent("types", key -> new ArrayList<JsonNodePath>());
types.add(walkEvent);
}
});
JsonSchema schema = factory.getSchema(schemaData, config);
ValidationResult result = schema.walk("\"hello\"", InputFormat.JSON, true);
assertFalse(result.getValidationMessages().isEmpty());

@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) result.getExecutionContext().getCollectorContext().get("types");
assertEquals(1, types.size());
assertEquals("", types.get(0).getInstanceLocation().toString());
assertEquals("/else", types.get(0).getSchema().getEvaluationPath().toString());
}

@Test
void walkValidateNull() {
String schemaData = "{\r\n"
+ " \"if\": {\r\n"
+ " \"const\": \"false\"\r\n"
+ " },\r\n"
+ " \"then\": {\r\n"
+ " \"type\": \"object\"\r\n"
+ " },\r\n"
+ " \"else\": {\r\n"
+ " \"type\": \"number\"\r\n"
+ " }\r\n"
+ "}";
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
config.setPathType(PathType.JSON_POINTER);
config.addKeywordWalkListener(ValidatorTypeCode.TYPE.getValue(), new JsonSchemaWalkListener() {

@Override
public WalkFlow onWalkStart(WalkEvent walkEvent) {
return WalkFlow.CONTINUE;
}

@Override
public void onWalkEnd(WalkEvent walkEvent, Set<ValidationMessage> validationMessages) {
@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) walkEvent.getExecutionContext()
.getCollectorContext()
.getCollectorMap()
.computeIfAbsent("types", key -> new ArrayList<JsonNodePath>());
types.add(walkEvent);
}
});
JsonSchema schema = factory.getSchema(schemaData, config);
ValidationResult result = schema.walk(null, true);
assertTrue(result.getValidationMessages().isEmpty());

@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) result.getExecutionContext().getCollectorContext().get("types");
assertEquals(2, types.size());
}

@Test
void walkNoValidate() {
String schemaData = "{\r\n"
+ " \"if\": {\r\n"
+ " \"const\": \"false\"\r\n"
+ " },\r\n"
+ " \"then\": {\r\n"
+ " \"type\": \"object\"\r\n"
+ " },\r\n"
+ " \"else\": {\r\n"
+ " \"type\": \"number\"\r\n"
+ " }\r\n"
+ "}";
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(VersionFlag.V202012);
SchemaValidatorsConfig config = new SchemaValidatorsConfig();
config.setPathType(PathType.JSON_POINTER);
config.addKeywordWalkListener(ValidatorTypeCode.TYPE.getValue(), new JsonSchemaWalkListener() {

@Override
public WalkFlow onWalkStart(WalkEvent walkEvent) {
return WalkFlow.CONTINUE;
}

@Override
public void onWalkEnd(WalkEvent walkEvent, Set<ValidationMessage> validationMessages) {
@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) walkEvent.getExecutionContext()
.getCollectorContext()
.getCollectorMap()
.computeIfAbsent("types", key -> new ArrayList<JsonNodePath>());
types.add(walkEvent);
}
});
JsonSchema schema = factory.getSchema(schemaData, config);
ValidationResult result = schema.walk("\"false\"", InputFormat.JSON, false);
assertTrue(result.getValidationMessages().isEmpty());

@SuppressWarnings("unchecked")
List<WalkEvent> types = (List<WalkEvent>) result.getExecutionContext().getCollectorContext().get("types");
assertEquals(2, types.size());
}
}
Loading