jsonschema icon indicating copy to clipboard operation
jsonschema copied to clipboard

check_schema always succeeds

Open ehault opened this issue 9 years ago • 7 comments

I have some schema issue and in trying to figure them out i made my tests simpler and simpler and I ended up with this:

lepthy@lepthy-apple:/tmp$ python3 -m venv venv
lepthy@lepthy-apple:/tmp$ . venv/bin/activate
(venv) lepthy@lepthy-apple:/tmp$ pip install jsonschema
Collecting jsonschema
  Using cached jsonschema-2.6.0-py2.py3-none-any.whl
Installing collected packages: jsonschema
Successfully installed jsonschema-2.6.0
(venv) lepthy@lepthy-apple:/tmp$ python
Python 3.6.0 (default, Dec 24 2016, 00:01:50) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import jsonschema
>>> schema = {1:1}
>>> jsonschema.Draft4Validator.check_schema(schema)
>>> 
>>>

I literally can't get check_schema to fail, is that expected?

ehault avatar Aug 01 '17 17:08 ehault

That's a valid schema.

There are certainly many invalid ones though. See e.g.:

>>> jsonschema.Draft4Validator.check_schema({"type": 12})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/Julian/.local/share/virtualenvs/jsonschema/site-packages/jsonschema/validators.py", line 83, in check_schema
    raise SchemaError.create_from(error)
SchemaError: 12 is not valid under any of the given schemas

Failed validating u'anyOf' in schema[u'properties'][u'type']:
    {u'anyOf': [{u'$ref': u'#/definitions/simpleTypes'},
                {u'items': {u'$ref': u'#/definitions/simpleTypes'},
                 u'minItems': 1,
                 u'type': u'array',
                 u'uniqueItems': True}]}

On instance[u'type']:
    12
12 is not valid under any of the given schemas

Failed validating u'anyOf' in schema[u'properties'][u'type']:
    {u'anyOf': [{u'$ref': u'#/definitions/simpleTypes'},
                {u'items': {u'$ref': u'#/definitions/simpleTypes'},
                 u'minItems': 1,
                 u'type': u'array',
                 u'uniqueItems': True}]}

On instance[u'type']:
    12

Julian avatar Aug 01 '17 17:08 Julian

Similar issue, I don't understand check_schema() purpose for a real error(such as: {1:1}) or typo error (such as: {"mixProperties": 1}) schema, it will ignore it(PS: for second scene, it's common at least). Only predefined schema key's name will be check. See related code:

[yancy@asus ~]$ pip freeze | grep jsonschema
jsonschema==3.0.1

$ vim jsonschema/validators.py
... ...
317                 for k, v in validators:      
318                     validator = self.VALIDATORS.get(k)       
319                     if validator is None:      
320                         continue    

If so, it is confused(I am learning json-schema knowledge). Since check_schema method name call check_xxx, why a error schema will be skipped? What is the purpose of the check_schema?

Or, have others reason for it? Thanks in advance !

uddmorningsun avatar May 30 '19 14:05 uddmorningsun

The specification says that unknown validators must be ignored.

Julian avatar May 30 '19 15:05 Julian

@Julian Thanks your reply, I see ! Based on your tips, I google related keywords and find some references

  • https://tools.ietf.org/html/draft-handrews-json-schema-01#section-4.3 (Draft 7)

uddmorningsun avatar May 31 '19 05:05 uddmorningsun

The specification says that unknown validators must be ignored.

If someone happens upon this with the same level of confusion and bewilderment as I did after not noticing a typo until some damage was done (I can validate things with my schema, but I can't be sure my schema is valid???), this trick may (or may not) help:

class SaferDraft7Validator(jsonschema.Draft7Validator):
    META_SCHEMA = {**jsonschema.Draft7Validator.META_SCHEMA, "additionalProperties": False}

And now this code works as expected:

jsonschema.validate({}, {1: 1}, SaferDraft7Validator)
# Exception: SchemaError: Additional properties are not allowed (1 was unexpected)

jsonschema.validate({}, {"mixProperties": 1}, SaferDraft7Validator)
# Exception: SchemaError: Additional properties are not allowed ('mixProperties' was unexpected)

jsonschema.validate({"a": "b"}, {"maxProperties": 0}, SaferDraft7Validator)
# Exception: ValidationError: {'a': 'b'} has too many properties

I think this behaviour should be supported in some way as an opt-in flag for this library. Happy to help out if such a PR would be welcome. This trick will tide me over in the meantime.


Update 2021-10-26: The above trick doesn't work with Draft202012Validator, but just changing additionalProperties to unevaluatedProperties seems to work for me so far (YMMV). I'll update this if I find more info.

class SaferDraft202012Validator(jsonschema.Draft202012Validator):
    META_SCHEMA = {**jsonschema.Draft202012Validator.META_SCHEMA, "unevaluatedProperties": False}

shabbyrobe avatar Jun 22 '20 10:06 shabbyrobe

Unfortunately this solution, while at the moment working is explicitely deprecated. Using it, I get the following warning:

 DeprecationWarning: Subclassing validator classes is not intended to be part of their public API. A future
 version will make doing so an error, as the behavior of subclasses isn't guaranteed to stay the same between
 releases of jsonschema. Instead, prefer composition of validators, wrapping them in an object owned
 entirely by the downstream library.
  class SaferDraft7Validator(Draft7Validator):

Does anyone here know from the top of their head, how to get typo warnings with this proposed composition of validators?

efokken-abb avatar Apr 28 '23 07:04 efokken-abb

Oh, it is quite easy: Wrap it in a function and simply change the meta schema for each instance:

from jsonschema import Draft7Validator

def SaferDraft7Validator():
    validator = Draft7Validator
    validator.META_SCHEMA = {
        **Draft7Validator.META_SCHEMA,
        "additionalProperties": False,
    }
    return validator

validator =  SaferDraft7Validator()

efokken-abb avatar Apr 28 '23 07:04 efokken-abb