python-jsonschema / jsonschema

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

Pick the deepest error among the most relevant ones in each subschema #1258

Open ilia1243 opened 2 months ago

ilia1243 commented 2 months ago

Improves best_match in the presence of anyOf / oneOf. Calculate the most relevant error in each separate subschema and choose the deepest one.

In particular, for anyOf / oneOf keywords with the only subschema, the best error is resolved as if the subschema was not enclosed by these keywords.

To reproduce:

from jsonschema import Draft202012Validator as Validator, exceptions

for applicator in "anyOf", "oneOf":
    # Should match {"properties": {"foo": {"minProperties": 2}}
    schema = {
        applicator: [
            {
                "properties": {
                    "foo": {
                        "minProperties": 2,
                        "properties": {"bar": {"type": "object"}},
                    },
                },
            },
        ],
    }
    instance = {"foo": {"bar": []}}
    error = exceptions.best_match(Validator(schema).iter_errors(instance))
    print(error)

Revert main code changes in commit https://github.com/python-jsonschema/jsonschema/commit/b20234e86c4dadf5d691400383a6fc0a1e9afc34 preserving the tests.

Closes: #1257


📚 Documentation preview 📚: https://python-jsonschema--1258.org.readthedocs.build/en/1258/

Julian commented 2 months ago

Thanks! I'll have a look at this in the next day or two but initially looks reasonable!