Skip to content

Allow format checkers to raise custom ValidationErrors #71

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

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,12 +293,15 @@ def validate_pattern(self, patrn, instance, schema):
yield ValidationError("%r does not match %r" % (instance, patrn))

def validate_format(self, format, instance, schema):
if (
self.format_checker is not None and
self.is_type(instance, "string") and
not self.format_checker.conforms(instance, format)
):
yield ValidationError("%r is not a %r" % (instance, format))
try:
if (
self.format_checker is not None and
self.is_type(instance, "string") and
not self.format_checker.conforms(instance, format)
):
yield ValidationError("%r is not a %r" % (instance, format))
except ValidationError as e:
yield e

def validate_minLength(self, mL, instance, schema):
if self.is_type(instance, "string") and len(instance) < mL:
Expand Down
10 changes: 10 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,16 @@ def test_it_validates_formats_if_a_checker_is_provided(self):
with self.assertRaises(ValidationError):
validator.validate("bar")

def test_it_raises_custom_errors_from_format_checkers(self):
message = "This is the custom error"
checker = mock.Mock(spec=FormatChecker)
validator = self.validator_class(
{"format": "foo"}, format_checker=checker
)
checker.conforms.side_effect = ValidationError(message)
with self.assertRaisesRegexp(ValidationError, message):
validator.validate("bar")


@load_json_cases(
"draft3/*.json", ignore_glob=os.path.join("draft3", "refRemote.json")
Expand Down