implement binary field size validation
This commit is contained in:
parent
bb19ba3eb6
commit
0b3af2052f
@ -448,7 +448,8 @@ class BinaryField(BaseField):
|
||||
"""A binary data field.
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
def __init__(self, max_bytes=None, **kwargs):
|
||||
self.max_bytes = max_bytes
|
||||
super(BinaryField, self).__init__(**kwargs)
|
||||
|
||||
def to_mongo(self, value):
|
||||
@ -456,3 +457,9 @@ class BinaryField(BaseField):
|
||||
|
||||
def to_python(self, value):
|
||||
return str(value)
|
||||
|
||||
def validate(self, value):
|
||||
assert isinstance(value, str)
|
||||
|
||||
if self.max_bytes is not None and len(value) > self.max_bytes:
|
||||
raise ValidationError('Binary value is too long')
|
||||
|
@ -516,5 +516,40 @@ class FieldTest(unittest.TestCase):
|
||||
|
||||
Attachment.drop_collection()
|
||||
|
||||
def test_binary_validation(self):
|
||||
"""Ensure that invalid values cannot be assigned to binary fields.
|
||||
"""
|
||||
class Attachment(Document):
|
||||
blob = BinaryField()
|
||||
|
||||
class AttachmentRequired(Document):
|
||||
blob = BinaryField(required=True)
|
||||
|
||||
class AttachmentSizeLimit(Document):
|
||||
blob = BinaryField(max_bytes=4)
|
||||
|
||||
Attachment.drop_collection()
|
||||
AttachmentRequired.drop_collection()
|
||||
AttachmentSizeLimit.drop_collection()
|
||||
|
||||
attachment = Attachment()
|
||||
attachment.validate()
|
||||
attachment.blob = 2
|
||||
self.assertRaises(ValidationError, attachment.validate)
|
||||
|
||||
attachment_required = AttachmentRequired()
|
||||
self.assertRaises(ValidationError, attachment_required.validate)
|
||||
attachment_required.blob = '\xe6\x00\xc4\xff\x07'
|
||||
attachment_required.validate()
|
||||
|
||||
attachment_size_limit = AttachmentSizeLimit(blob='\xe6\x00\xc4\xff\x07')
|
||||
self.assertRaises(ValidationError, attachment_size_limit.validate)
|
||||
attachment_size_limit.blob = '\xe6\x00\xc4\xff'
|
||||
attachment_size_limit.validate()
|
||||
|
||||
Attachment.drop_collection()
|
||||
AttachmentRequired.drop_collection()
|
||||
AttachmentSizeLimit.drop_collection()
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
Loading…
x
Reference in New Issue
Block a user