Skip to content

Add a deprecation warning to validate_for if schema doesn't exist #484

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Nov 18, 2018
Merged
28 changes: 27 additions & 1 deletion jsonschema/tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,7 +1100,7 @@ def test(self, format=format):
setattr(TestBuiltinFormats, name, test)


class TestValidatorFor(TestCase):
class TestValidatorFor(SynchronousTestCase):
def test_draft_3(self):
schema = {"$schema": "http://json-schema.org/draft-03/schema"}
self.assertIs(
Expand Down Expand Up @@ -1194,6 +1194,32 @@ def test_validator_for_jsonschema_default(self):
def test_validator_for_custom_default(self):
self.assertIs(validators.validator_for({}, default=None), None)

def test_warns_if_meta_schema_specified_was_not_found(self):
self.assertWarns(
category=DeprecationWarning,
message=(
"This metaschema was not found but going to validate with the "
"latest draft. This will raise an error in future. "
),
# https://tm.tl/9363 :'(
filename=sys.modules[self.assertWarns.__module__].__file__,

f=validators.validator_for,
schema={u"$schema": 'unknownSchema'},
default={},
)

def test_doesnt_warns_if_meta_schema_not_specified(self):
validators.validator_for(schema={}, default={}),
self.assertFalse(self.flushWarnings())

def test_latest_schema_used_if_meta_schema_not_specified(self):
lastestSchema = validators.meta_schemas[
"http://json-schema.org/draft-07/schema#"
]
schema = validators.validator_for(schema={}, default=lastestSchema)
self.assertEqual(schema, lastestSchema)


class TestValidate(TestCase):
def assertUses(self, schema, Validator):
Expand Down
13 changes: 11 additions & 2 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,15 @@ def validator_for(schema, default=_LATEST_VERSION):
If unprovided, the default is to return
the latest supported draft.
"""
if schema is True or schema is False:
if schema is True or schema is False or not u"$schema" in schema:
return default
return meta_schemas.get(schema.get(u"$schema", u""), default)
if schema[u"$schema"] not in meta_schemas:
warn(
(
"This metaschema was not found but going to validate with the "
"latest draft. This will raise an error in future. "
),
DeprecationWarning,
stacklevel=2,
)
return meta_schemas.get(schema[u"$schema"], _LATEST_VERSION)