def test_load_returns_none_if_no_item_is_found(self): self.manager.get.return_value = () field = ReferenceTargetField(target_cls=lambda: self.modelMockCls, ) val = random.randint(0, 1000) saved = field._load(val) self.assertIsNone(saved.value) self.manager.get.assert_called_once_with({'_id': val})
def test_load_creates_a_cached_obj(self): self.manager.get.return_value = () field = ReferenceTargetField(target_cls=lambda: self.modelMockCls, ) val = random.randint(0, 1000) saved = field._load(val) self.assertTrue(isinstance(saved, CachedObj))
def test_serialize_no_value_transformer_item_does_notexists(self): field = ReferenceTargetField(target_cls=lambda: self.modelMockCls, ) self.manager.exists.return_value = False val = random.randint(0, 1000) with self.assertRaises(NotFoundError): field._serialize(val)
def test_serialize_no_value_transformer_item_exists(self): field = ReferenceTargetField(target_cls=self.modelMockCls, ) self.manager.exists.return_value = True val = random.randint(0, 1000) serialized = field._serialize(val) self.assertEqual(val, serialized) self.manager.exists.assert_called_once_with({'_id': val})
def test_serialize_no_value_transformer_no_exists(self): field = ReferenceTargetField(target_cls=self.modelMockCls, validate_exists=False) val = random.randint(0, 1000) serialized = field._serialize(val) self.assertEqual(val, serialized) self.manager.exists.assert_not_called()
def test_load_returns_found_item(self): result = random.randint(0, 1000) target_field = "target" self.manager.get.return_value = [result] field = ReferenceTargetField(target_cls=lambda: self.modelMockCls, target_field=target_field) val = random.randint(0, 1000) saved = field._load(val) self.assertEqual(saved.value, result) self.manager.get.assert_called_once_with({target_field: val})
class AnswerModel(LocationBasedModel): fields = { "question": ReferenceTargetField( target_cls=_get_question_model, value_transformer=lambda v: hex_str_to_id_obj(v.value._id), load_from="question_id", dump_to='question_id') } @classmethod def get_scheme_cls(cls, class_to_create=None): class_to_create = class_to_create or cls base_schema = super(AnswerModel, cls).get_scheme_cls(class_to_create) class AnswerSchema(base_schema): text = fields.String() score = fields.Integer(default=0) question_id = ReverseIdField() return AnswerSchema