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
Changes from 1 commit
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
Next Next commit
Add support for marshmallow Regexp validator
Axmacher authored and Axmacher committed Jan 30, 2017
commit 8fc9c3789ea58f2fa9d9cb3f6ee0574b4c555061
4 changes: 3 additions & 1 deletion marshmallow_jsonschema/base.py
Original file line number Diff line number Diff line change
@@ -6,7 +6,8 @@
from marshmallow.class_registry import get_class
from marshmallow.compat import text_type, binary_type, basestring

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


__all__ = ['JSONSchema']
@@ -73,6 +74,7 @@
validate.Length: handle_length,
validate.OneOf: handle_one_of,
validate.Range: handle_range,
validate.Regexp: handle_regexp
}


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

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
@@ -43,6 +43,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):
7 changes: 7 additions & 0 deletions tests/test_dump.py
Original file line number Diff line number Diff line change
@@ -192,3 +192,10 @@ class UserSchema(Schema):
json_schema = JSONSchema()
dumped = json_schema.dump(schema).data
assert dumped['properties']['favourite_colour'] == {'type': 'string'}

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