better validation of keyword arguments in model constructor

This commit is contained in:
Itai Shirav 2016-06-23 18:34:52 +03:00
parent b08f1b3688
commit 92e8b8259f
2 changed files with 26 additions and 3 deletions

View File

@ -30,11 +30,20 @@ class Model(object):
Creates a model instance, using keyword arguments as field values.
Since values are immediately converted to their Pythonic type,
invalid values will cause a ValueError to be raised.
Unrecognized field names will cause an AttributeError.
'''
super(Model, self).__init__()
# Assign field values from keyword arguments
for name, value in kwargs.iteritems():
field = self.get_field(name)
if field:
setattr(self, name, value)
else:
raise AttributeError('%s does not have a field called %s' % (self.__class__.__name__, name))
# Assign default values for fields not included in the keyword arguments
for name, field in self._fields:
val = kwargs.get(name, field.default)
setattr(self, name, val)
if name not in kwargs:
setattr(self, name, field.default)
def __setattr__(self, name, value):
field = self.get_field(name)

View File

@ -10,7 +10,7 @@ from infi.clickhouse_orm.engines import *
class ModelTestCase(unittest.TestCase):
def test_defaults(self):
# Check that all fields have their defaults
# Check that all fields have their explicit or implicit defaults
instance = SimpleModel()
self.assertEquals(instance.date_field, datetime.date(1970, 1, 1))
self.assertEquals(instance.datetime_field, datetime.datetime(1970, 1, 1, tzinfo=pytz.utc))
@ -31,6 +31,20 @@ class ModelTestCase(unittest.TestCase):
for name, value in kwargs.items():
self.assertEquals(kwargs[name], getattr(instance, name))
def test_assignment_error(self):
# Check non-existing field during construction
with self.assertRaises(AttributeError):
instance = SimpleModel(int_field=7450, pineapple='tasty')
# Check invalid field values during construction
with self.assertRaises(ValueError):
instance = SimpleModel(int_field='nope')
with self.assertRaises(ValueError):
instance = SimpleModel(date_field='nope')
# Check invalid field values during assignment
instance = SimpleModel()
with self.assertRaises(ValueError):
instance.datetime_field = datetime.timedelta(days=1)
def test_string_conversion(self):
# Check field conversion from string during construction
instance = SimpleModel(date_field='1973-12-06', int_field='100', float_field='7')