santhosh-tekuri/jsonschema

Validation mystery

Closed this issue · 2 comments

Hi, I have a schema which looks like this attached file actual-schema.json

I am validating this file agains the data filecli.jsonfiles.

actual-schema.json.txt
cli.json.txt

Validation code looks like this:

func TestValidate(t *testing.T) {
	sch, err := jsonschema.Compile("testdata/actual-schema.json")
	if err != nil {
		log.Fatalf("%#v", err)
	}

	data, err := ioutil.ReadFile("testdata/cli.json")
	if err != nil {
		log.Fatal(err)
	}

	var v interface{}
	if err := json.Unmarshal(data, &v); err != nil {
		log.Fatal(err)
	}

	if err = sch.Validate(v); err != nil {
		log.Fatalf("%#v", err)
	}
}

If my cli.json file looks like this:

{
    "test": {
        "abc": {
            "ABC-noABC": "abc-data",
            "def": {
                "DEF": "def-data"
            }
        }
    }
}

where required tag ABC is missing, I get a right error message from the program like this:
time="2022-06-27T22:12:15-04:00" level=fatal msg="[I#] [S#] doesn't validate with actual-schema.json#\n [I#/test] [S#/properties/test/anyOf] anyOf failed\n [I#/test/abc] [S#/properties/test/anyOf/0/properties/abc/required] missing properties: 'ABC'"

This text passes the validation.
{
    "test": {
        "abc": {
            "ABC": "abc-data",
            "def": {
                "DEF-missing": "def-data"
            }
        }
    }
}

But, if I make the "DEF" miss which is also a required argument, the program does not prompt with an error.

Can someone clarify why it passes?

Thank you.

The second one passes the validation. This is the expected behaviour.

the second anyOf's first condition is satisfied (i.e, the current has property named ABC of type string).
so the second condition is not checked(which says it has property def with sub property DEF)

anyOf keyword means at least one of the condition should be satisfied.
if you want all the conditions to be satisfied, you should use allOf keyword instead of anyOf

Thanks Santosh.