def test_cast_to_class(self): class SomeCastingClass(object): def __init__(self, value): self.value = value @classmethod def cast_to_class(cls, value): return cls(value) int_val = 8 str_val = "some_str" unicode_val = u"some_unicode" self.assertIs(8, utils.cast_to_class(int_val, int)) self.assertIsInstance(utils.cast_to_class(int_val, float), float) self.assertIsInstance(utils.cast_to_class(str_val, unicode), unicode) self.assertIsInstance(utils.cast_to_class(unicode_val, str), str) self.assertIsInstance(utils.cast_to_class(unicode_val, SomeCastingClass), SomeCastingClass)
def ensure_type(self, value): """ Cast `value` to type which field could store. """ # If Field is not strongly typed, no preparation is need if self.field_type is None: return value # If value is None, no preparation is need if value is None: return value # If value is Dictionary and type is Model we should create model with data from dict return cast_to_class(value, self.field_type)
def cast_inner_item(cls, item): """ Cast `value` to `inner_type` """ return cast_to_class(item, cls.inner_type)