Skip to content

Instantly share code, notes, and snippets.

@brondsem
Created April 27, 2011 22:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brondsem/945328 to your computer and use it in GitHub Desktop.
Save brondsem/945328 to your computer and use it in GitHub Desktop.
diff --git a/ming/orm/property.py b/ming/orm/property.py
index 2ad5dcf..296d8c7 100644
--- a/ming/orm/property.py
+++ b/ming/orm/property.py
@@ -1,5 +1,6 @@
-from ming.base import Field
+from ming.base import Field, Object
from ming.utils import LazyProperty
+from ming.schema import SchemaItem
from .base import session, state, mapper, lookup_class
from .icollection import InstrumentedList
@@ -60,6 +61,9 @@ class FieldProperty(ORMProperty):
return getattr(st.document, self.name)
def __set__(self, instance, value):
+ si = SchemaItem.make(self.field_type, *self.args, **self.kwargs)
+ si.validate(value)
+
st = state(instance)
st.soil()
st.document[self.name] = value
diff --git a/ming/schema.py b/ming/schema.py
index f18c19b..f9fd0e1 100644
--- a/ming/schema.py
+++ b/ming/schema.py
@@ -200,6 +200,8 @@ class FancySchemaItem(SchemaItem):
self.__class__.__name__, self.required)
def validate(self, value, **kw):
+ if value is None and self.required:
+ value = Missing
if value is Missing:
if self.required:
raise Invalid('Missing field', value, None)
diff --git a/ming/tests/test_orm.py b/ming/tests/test_orm.py
index 0282f80..eb1511c 100644
--- a/ming/tests/test_orm.py
+++ b/ming/tests/test_orm.py
@@ -126,6 +126,15 @@ class TestBasicMapping(TestCase):
q = self.Basic.query.find()
self.assertEqual(q.count(), 0)
+ def test_validate_upon_set(self):
+ doc = self.Basic(a=1)
+ try:
+ doc.a = 'foobar'
+ except S.Invalid:
+ pass
+ else:
+ raise AssertionError('Invalid exception expected')
+
def test_query(self):
doc = self.Basic(a=1, b=[2,3], c=dict(d=4, e=5))
self.session.flush()
diff --git a/ming/tests/test_schema.py b/ming/tests/test_schema.py
index ee43d17..dccdc50 100644
--- a/ming/tests/test_schema.py
+++ b/ming/tests/test_schema.py
@@ -105,6 +105,10 @@ class TestSchemaItem(TestCase):
si = S.SchemaItem.make(dict(version=4))
self.assertEqual(si.validate(dict(version=4)), dict(version=4))
self.assertRaises(S.Invalid, si.validate, dict(version=3))
+
+ def test_required_none(self):
+ si = S.SchemaItem.make(int, required=True)
+ self.assertRaises(S.Invalid, si.validate, None)
def test_missing(self):
self.assertEqual(repr(S.Missing), '<Missing>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment