From 0b3af2052f51dc7e64d1d8d8e1ab33727ec5d32a Mon Sep 17 00:00:00 2001 From: Rached Ben Mustapha Date: Mon, 8 Mar 2010 17:06:52 +0100 Subject: [PATCH] implement binary field size validation --- mongoengine/fields.py | 9 ++++++++- tests/fields.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/mongoengine/fields.py b/mongoengine/fields.py index 29c86660..fcae63ee 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -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') diff --git a/tests/fields.py b/tests/fields.py index fc2edb2c..986f0e26 100644 --- a/tests/fields.py +++ b/tests/fields.py @@ -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()