Skip to content

Commit

Permalink
Merge 7ec388f into b433ecc
Browse files Browse the repository at this point in the history
  • Loading branch information
wblxyxolbkhv committed May 19, 2021
2 parents b433ecc + 7ec388f commit fd3dc25
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ schema = {
'required': ['foo', 'bar']
}

class SomeMode(models.Model):
class SomeModel(models.Model):
some_field = models.JSONField(validators=[JSONFieldSchemaValidator(schema)])

```
7 changes: 7 additions & 0 deletions django_json_field_schema_validator/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

from django.core.exceptions import ValidationError
import jsonschema
from django.utils.deconstruct import deconstructible


@deconstructible
class JSONFieldSchemaValidator:
def __init__(self, schema: dict, draft_version=7):
self.schema = schema
Expand All @@ -30,6 +32,11 @@ def __call__(self, value):

return value

def __eq__(self, other):
if not hasattr(other, 'deconstruct'):
return False
return self.deconstruct() == other.deconstruct()

def _extract_errors(
self,
errors: Iterable[jsonschema.ValidationError],
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

base_dir = path.abspath(path.dirname(__file__))

__version__ = '0.0.1'
__version__ = '0.0.2'

# Get the long description from the README file
with open(path.join(base_dir, 'README.md'), encoding='utf-8') as f:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import importlib

import pytest
from django.core.exceptions import ValidationError

Expand Down Expand Up @@ -47,3 +49,23 @@ def test_validation_with_context():
validator = JSONFieldSchemaValidator(schema)
with pytest.raises(ValidationError):
validator({"items": [{}, 3, "foo"]})


def test_deconstruct():
schema = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {"id": {"type": "number"}, "name": {"type": "string"}},
"required": ["id", "name"],
}
validator = JSONFieldSchemaValidator(schema)
path, args, kwargs = validator.deconstruct()

klass_name = path.split('.')[-1]
module_name = path.replace(f'.{klass_name}', '')
module = importlib.import_module(module_name)
klass = getattr(module, klass_name)

restored_validator = klass(*args, **kwargs)

assert restored_validator == validator

0 comments on commit fd3dc25

Please sign in to comment.