networknt / json-schema-validator

A fast Java JSON schema validator that supports draft V4, V6, V7, V2019-09 and V2020-12
Apache License 2.0
807 stars 320 forks source link

Keyword Walker not walking root of then/else #1009

Closed b-wils closed 3 months ago

b-wils commented 3 months ago

It seems like the keyword walker is not visiting the then/else nodes that are part of an if clause. Here is a minimal repro I put together:

// schema.json
{
    "if": {
      "const": "false"
    },
    "then": {
      "type": "object"
    },
    "else": {
      "type": "number"
    }
  }
  // Main.java 
SchemaValidatorsConfig schemaValidatorsConfig = new SchemaValidatorsConfig();
schemaValidatorsConfig.addKeywordWalkListener(ValidatorTypeCode.TYPE.getValue(), new TypeKeywordListener());
JsonSchemaFactory jsonSchemaFactory =
        JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
this.schema = jsonSchemaFactory.getSchema(schemaString, schemaValidatorsConfig);

ValidationResult result = profileSchema.walk(json, true);

  private static class TypeKeywordListener implements JsonSchemaWalkListener {

    @Override
    public WalkFlow onWalkStart(WalkEvent keywordWalkEvent) {
      System.out.println("WALK START");
      return WalkFlow.CONTINUE;
    }

    @Override
    public void onWalkEnd(WalkEvent keywordWalkEvent, Set<ValidationMessage> validationMessages) {
      System.out.println("WALK END");
    }
  }

I would expect this to print, but it doesn't at all. This does work if I add type to other nodes, for example the root or in a more fleshed out schema. I'm currently running on 1.3.3. I saw there was recent refactor with walk in 1.4.0 so curious if that may help. It's a non trivial amount of work for me to upgrade, so wanted to check first to see if this is/was known.

justin-tay commented 3 months ago

Thanks for reporting the issue. It looks like there has always been an issue with the if validator when walking with the validate schema option enabled.