1. Waldemar Kornewald
  2. djangotoolbox

Commits

Waldemar Kornewald  committed 640a13a

Adds a test case for nice TypeErrors in EmbeddedModelField's seriaization method, plus one fix to make the tests pass (nice error messages should also be used in the "untyped" case) Contributed by Jonas Haag.

  • Participants
  • Parent commits 40ebd7d
  • Branches default

Comments (0)

Files changed (2)

File djangotoolbox/fields.py

View file
  • Ignore whitespace
         embedded_instance = super(EmbeddedModelField, self).pre_save(model_instance, add)
         if embedded_instance is None:
             return None, None
-        if self.embedded_model is not None and \
-                not isinstance(embedded_instance, self.embedded_model):
-            raise TypeError("Expected instance of type %r, not %r"
-                            % (type(self.embedded_model), type(embedded_instance)))
+
+        model = self.embedded_model or models.Model
+        if not isinstance(embedded_instance, model):
+            raise TypeError("Expected instance of type %r, not %r" % (
+                            type(model), type(embedded_instance)))
 
         data = dict((field.name, field.pre_save(embedded_instance, add))
                     for field in embedded_instance._meta.fields)

File djangotoolbox/tests.py

View file
  • Ignore whitespace
 
     class EmbeddedModelFieldModel(models.Model):
         simple = EmbeddedModelField('EmbeddedModel', null=True)
+        simple_untyped = EmbeddedModelField(null=True)
         typed_list = ListField(EmbeddedModelField('SetModel'))
         untyped_list = ListField(EmbeddedModelField())
         untyped_dict = DictField(EmbeddedModelField())
         self.assertEqual(instance.simple.auto_now_add, auto_now_add)
         self.assertGreater(instance.simple.auto_now, auto_now)
 
+    def test_error_messages(self):
+        for kwargs in (
+            {'simple_untyped' : 42},
+            {'simple' : 42}
+        ):
+            self.assertRaisesRegexp(TypeError, "Expected instance of type",
+                                    EmbeddedModelFieldModel(**kwargs).save)
+
     def test_typed_listfield(self):
         EmbeddedModelFieldModel.objects.create(
             typed_list=[SetModel(setfield=range(3)), SetModel(setfield=range(9))]