python-jsonschema / jsonschema

An implementation of the JSON Schema specification for Python
https://python-jsonschema.readthedocs.io
MIT License
4.58k stars 578 forks source link

Issue with oneOf validation #1194

Closed lbpelegrini closed 9 months ago

lbpelegrini commented 9 months ago

I have the following schema and value:

Schema: { "type":"object", "required":["my_date"], "properties":{ "my_date":{ "title":"My date", "type":"array", "minItems":1, "items":{ "type":"object", "required":["value"], "properties":{ "value":{ "title":"My date", "type":"string", "oneOf":[ { "type":"string", "format":"date" }, { "type":"string", "format":"date-time" } ] } } } } } }

Json: { "my_date":[ { "value": "2021-01-01" } ] }

Error: "'2021-01-01' is valid under each of {'type': 'string', 'format': 'date-time'}, {'type': 'string', 'format': 'date'}"

It looks like there's something wrong with the oneOf condition, since I ran some tests removing the format checkers, or making the formats equal (using "date" in both) and it always result in error when using more than one condition in oneOf.

I don't know if that's the expected behaviour, but a test with www.jsonschemavalidator.net resulted no errors.

Version: 4.20.0

Julian commented 9 months ago

Please include what code you are running.

lbpelegrini commented 9 months ago
class Validator:
    def execute(schema, json):
        validator = jsonschema.Draft202012Validator(schema)
        for error in sorted(validator.iter_errors(json), key=str):
            message = error.message
Julian commented 9 months ago

You haven't enabled format validation, so both your oneOf schemas always match any string (sounds like the other site you tried isn't fully compliant with the spec). See the FAQ in the docs for how to do so.

Julian commented 9 months ago

More specifically https://python-jsonschema.readthedocs.io/en/stable/validate/#validating-formats

lbpelegrini commented 9 months ago

That was exactly the problem, thank you so much for the support.

Julian commented 9 months ago

Glad to hear, my pleasure! (Sorry, this is obviously something that trips up everyone essentially, but it's spec'ed behavior...)