From 12e6f573adbf825c74042f15b70600341220674b Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Mon, 2 Dec 2019 01:16:32 +0100 Subject: [PATCH] Refs #26552 -- Added test for reloading the database with self-referential objects. --- tests/backends/base/test_creation.py | 24 +++++++++++++++++++++++- tests/backends/models.py | 5 +++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/tests/backends/base/test_creation.py b/tests/backends/base/test_creation.py index 1d345c611b6..19a39150219 100644 --- a/tests/backends/base/test_creation.py +++ b/tests/backends/base/test_creation.py @@ -7,7 +7,7 @@ from django.db.backends.base.creation import ( ) from django.test import SimpleTestCase, TransactionTestCase -from ..models import Object, ObjectReference +from ..models import Object, ObjectReference, ObjectSelfReference def get_connection_copy(): @@ -101,3 +101,25 @@ class TestDeserializeDbFromString(TransactionTestCase): obj_ref = ObjectReference.objects.get() self.assertEqual(obj.obj_ref, obj_ref) self.assertEqual(obj_ref.obj, obj) + + def test_self_reference(self): + # serialize_db_to_string() and deserialize_db_from_string() handles + # self references. + obj_1 = ObjectSelfReference.objects.create(key='X') + obj_2 = ObjectSelfReference.objects.create(key='Y', obj=obj_1) + obj_1.obj = obj_2 + obj_1.save() + # Serialize objects. + with mock.patch('django.db.migrations.loader.MigrationLoader') as loader: + # serialize_db_to_string() serializes only migrated apps, so mark + # the backends app as migrated. + loader_instance = loader.return_value + loader_instance.migrated_apps = {'backends'} + data = connection.creation.serialize_db_to_string() + ObjectSelfReference.objects.all().delete() + # Deserialize objects. + connection.creation.deserialize_db_from_string(data) + obj_1 = ObjectSelfReference.objects.get(key='X') + obj_2 = ObjectSelfReference.objects.get(key='Y') + self.assertEqual(obj_1.obj, obj_2) + self.assertEqual(obj_2.obj, obj_1) diff --git a/tests/backends/models.py b/tests/backends/models.py index 277a3a12038..87809b84a8d 100644 --- a/tests/backends/models.py +++ b/tests/backends/models.py @@ -102,6 +102,11 @@ class ObjectReference(models.Model): return str(self.obj_id) +class ObjectSelfReference(models.Model): + key = models.CharField(max_length=3, unique=True) + obj = models.ForeignKey('ObjectSelfReference', models.SET_NULL, null=True) + + class RawData(models.Model): raw_data = models.BinaryField()