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

Regexp support #72

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
from .compat import text_type, binary_type, basestring, dot_data_backwards_compatable
from marshmallow.decorators import post_dump

from .validation import handle_length, handle_one_of, handle_range
from .validation import (handle_length, handle_one_of, handle_range,
handle_regexp)


__all__ = (
Expand Down Expand Up @@ -77,6 +78,7 @@
validate.Length: handle_length,
validate.OneOf: handle_one_of,
validate.Range: handle_range,
validate.Regexp: handle_regexp
}


Expand Down
26 changes: 26 additions & 0 deletions marshmallow_jsonschema/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,29 @@ def handle_range(schema, field, validator, parent_schema):
schema['maximum'] = validator.max

return schema


def handle_regexp(schema, field, validator, parent_schema):
"""Adds validation logic for ``marshmallow.validate.Regexp``, setting the
values appropriately for ``fields.String`` and its subclasses.

Args:
schema (dict): The original JSON schema we generated. This is what we
want to post-process.
field (fields.Field): The field that generated the original schema and
who this post-processor belongs to.
validator (marshmallow.validate.Regexp): The validator attached to the
passed in field.
parent_schema (marshmallow.Schema): The Schema instance that the field
belongs to.

Returns:
dict: A, possibly, new JSON Schema that has been post processed and
altered.
"""
if not isinstance(field, fields.String):
Copy link
Contributor

Choose a reason for hiding this comment

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

I recommend raising an UnsupportedValueError here as I did for other validators. marshmallow will fail on non-strings anyway:

>>> from marshmallow import fields
>>> from marshmallow.validate import Regexp
>>> f = fields.Integer(validate=Regexp(".*"))
>>> f.deserialize(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/lynx/projects/marshmallow-jsonschema/.venv/lib/python3.7/site-packages/marshmallow/fields.py", line 301, in deserialize
    self._validate(output)
  File "/home/lynx/projects/marshmallow-jsonschema/.venv/lib/python3.7/site-packages/marshmallow/fields.py", line 224, in _validate
    r = validator(value)
  File "/home/lynx/projects/marshmallow-jsonschema/.venv/lib/python3.7/site-packages/marshmallow/validate.py", line 362, in __call__
    if self.regex.match(value) is None:
TypeError: expected string or bytes-like object

Custom fields have to be handled with care though as they are not required to be an instance of fields.String. Though they are not supported yet, there is an attempt in #22.

return schema

if validator.regex and getattr(validator.regex, 'pattern', None):
schema['pattern'] = validator.regex.pattern
return schema
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class UserSchema(Schema):
validate=validate.Length(min=1, max=3))
github = fields.Nested(GithubProfile)
const = fields.String(validate=validate.Length(equal=50))
hex_number = fields.String(validate=validate.Regexp('^[a-fA-F0-9]+$'))


class BaseTest(unittest.TestCase):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_dump.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,3 +486,11 @@ class TestSchema(Schema):
json_schema = JSONSchema()
dumped = dot_data_backwards_compatable(json_schema.dump(schema))
assert 'required' not in dumped['definitions']['TestSchema']


def test_regexp_validator():
schema = UserSchema()
json_schema = JSONSchema()
dumped = dot_data_backwards_compatable(json_schema.dump(schema))
_validate_schema(dumped)
assert dumped['properties']['hex_number']['pattern'] == '^[a-fA-F0-9]+$'