Skip to content

Raise exception if validator mutates instance #1339

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: 15 additions & 0 deletions jsonschema/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,21 @@ def __str__(self):
)


class MutatingValidator(Exception):
"""
A validator mutated the instance.
"""

def __init__(self, validator: Any) -> None:
self.validator = validator

def __str__(self) -> str:
return (
f"Validator {self.validator!r} mutated the instance. "
f"This can cause failures for later validators."
)


class FormatError(Exception):
"""
Validating a format failed.
Expand Down
11 changes: 11 additions & 0 deletions jsonschema/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from urllib.request import urlopen
from warnings import warn
import contextlib
import copy
import json
import reprlib
import warnings
Expand Down Expand Up @@ -380,7 +381,12 @@ def iter_errors(self, instance, _schema=None):
return

for validator, k, v in validators:
instance_clone = copy.deepcopy(instance)
errors = validator(self, v, instance, _schema) or ()
if instance != instance_clone:
yield exceptions.MutatingValidator(validator)
del instance_clone

for error in errors:
# set details if not already set by the called fn
error._set(
Expand Down Expand Up @@ -428,7 +434,12 @@ def descend(
if validator is None:
continue

instance_clone = copy.deepcopy(instance)
errors = validator(evolved, v, instance, schema) or ()
if instance != instance_clone:
yield exceptions.MutatingValidator(validator)
del instance_clone

for error in errors:
# set details if not already set by the called fn
error._set(
Expand Down
Loading