Skip to content
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

[Issue24] Prevent Schema Mutation #26

Merged
merged 5 commits into from
Dec 28, 2021
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ coverage.xml
*.py,cover
.hypothesis/
.pytest_cache/
reports/

# Translations
*.mo
Expand Down
5 changes: 4 additions & 1 deletion openapi_schema_validator/validators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from copy import deepcopy

from jsonschema import _legacy_validators, _utils, _validators
from jsonschema.validators import create

Expand Down Expand Up @@ -63,7 +65,8 @@ def __init__(self, *args, **kwargs):

def iter_errors(self, instance, _schema=None):
if _schema is None:
_schema = self.schema
# creates a copy by value from schema to prevent mutation
_schema = deepcopy(self.schema)
Copy link
Contributor

@jparise jparise Dec 28, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this could be a shallow copy (_schema = self.schema.copy()), at least for the specific issue that's being addressed by this fix (because we only mutate by adding a new key). That would be a little more memory efficient than a full (deep) object copy.


# append defaults to trigger validator (i.e. nullable)
if 'nullable' not in _schema:
Expand Down
22 changes: 22 additions & 0 deletions tests/unit/test_shortcut.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from openapi_schema_validator import validate
from unittest import TestCase


class ValidateTest(TestCase):
def test_validate_does_not_mutate_schema_adding_nullable_key(self):
schema = {
"type": "object",
'properties': {
'email': {
'type': 'string'
},
'enabled': {
'type': 'boolean',
}
},
'example': {'enabled': False, 'email': "foo@bar.com"}
}

validate({"email": "foo@bar.com"}, schema)

self.assertTrue("nullable" not in schema["properties"]["email"].keys())