diff options
| author | sarahboyce <sarahvboyce95@gmail.com> | 2022-04-19 13:21:23 +0200 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2022-04-21 10:12:28 +0200 |
| commit | cd4da34fc1f1df08f593e461b2f670bfd61d0d2f (patch) | |
| tree | 315cd3eba3bfee07fca59a1cff6405ac6923a379 /tests/generic_relations | |
| parent | 1ed8ca43f61138b8f8d6f92106c27060753ed4e7 (diff) | |
Fixed #33004 -- Made saving objects with unsaved GenericForeignKey raise ValueError.
This aligns to the behaviour of OneToOneField and ForeignKey fields.
Thanks Jonny Park for the initial patch.
Diffstat (limited to 'tests/generic_relations')
| -rw-r--r-- | tests/generic_relations/tests.py | 29 |
1 files changed, 20 insertions, 9 deletions
diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py index 7c49e218dd..1ee14f5381 100644 --- a/tests/generic_relations/tests.py +++ b/tests/generic_relations/tests.py @@ -1,8 +1,7 @@ from django.contrib.contenttypes.models import ContentType from django.core.exceptions import FieldError -from django.db import IntegrityError from django.db.models import Q -from django.test import SimpleTestCase, TestCase +from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ( AllowsNullGFK, @@ -501,14 +500,26 @@ class GenericRelationsTests(TestCase): with self.assertRaisesMessage(FieldError, msg): TaggedItem.objects.get(content_object="") - def test_unsaved_instance_on_generic_foreign_key(self): - """ - Assigning an unsaved object to GenericForeignKey should raise an - exception on model.save(). - """ + def test_unsaved_generic_foreign_key_parent_save(self): + quartz = Mineral(name="Quartz", hardness=7) + tagged_item = TaggedItem(tag="shiny", content_object=quartz) + msg = ( + "save() prohibited to prevent data loss due to unsaved related object " + "'content_object'." + ) + with self.assertRaisesMessage(ValueError, msg): + tagged_item.save() + + @skipUnlessDBFeature("has_bulk_insert") + def test_unsaved_generic_foreign_key_parent_bulk_create(self): quartz = Mineral(name="Quartz", hardness=7) - with self.assertRaises(IntegrityError): - TaggedItem.objects.create(tag="shiny", content_object=quartz) + tagged_item = TaggedItem(tag="shiny", content_object=quartz) + msg = ( + "bulk_create() prohibited to prevent data loss due to unsaved related " + "object 'content_object'." + ) + with self.assertRaisesMessage(ValueError, msg): + TaggedItem.objects.bulk_create([tagged_item]) def test_cache_invalidation_for_content_type_id(self): # Create a Vegetable and Mineral with the same id. |
