Waldemar Kornewald avatar 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.

Comments (0)

Files changed (2)

djangotoolbox/fields.py

         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)

djangotoolbox/tests.py

 
     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))]
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.