summaryrefslogtreecommitdiff
path: root/tests/serializers/test_natural.py
blob: b5b35708c66c70049e01d276862e3ba26d0bfba3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
from django.core import serializers
from django.db import connection
from django.test import TestCase

from .models import (
    Child,
    FKAsPKNoNaturalKey,
    FKDataNaturalKey,
    NaturalKeyAnchor,
    NaturalKeyThing,
    NaturalPKWithDefault,
)
from .tests import register_tests


class NaturalKeySerializerTests(TestCase):
    pass


def natural_key_serializer_test(self, format):
    # Create all the objects defined in the test data
    with connection.constraint_checks_disabled():
        objects = [
            NaturalKeyAnchor.objects.create(id=1100, data="Natural Key Anghor"),
            FKDataNaturalKey.objects.create(id=1101, data_id=1100),
            FKDataNaturalKey.objects.create(id=1102, data_id=None),
        ]
    # Serialize the test database
    serialized_data = serializers.serialize(
        format, objects, indent=2, use_natural_foreign_keys=True
    )

    for obj in serializers.deserialize(format, serialized_data):
        obj.save()

    # Assert that the deserialized data is the same
    # as the original source
    for obj in objects:
        instance = obj.__class__.objects.get(id=obj.pk)
        self.assertEqual(
            obj.data,
            instance.data,
            "Objects with PK=%d not equal; expected '%s' (%s), got '%s' (%s)"
            % (
                obj.pk,
                obj.data,
                type(obj.data),
                instance,
                type(instance.data),
            ),
        )


def natural_key_test(self, format):
    book1 = {
        "data": "978-1590597255",
        "title": "The Definitive Guide to Django: Web Development Done Right",
    }
    book2 = {"data": "978-1590599969", "title": "Practical Django Projects"}

    # Create the books.
    adrian = NaturalKeyAnchor.objects.create(**book1)
    james = NaturalKeyAnchor.objects.create(**book2)

    # Serialize the books.
    string_data = serializers.serialize(
        format,
        NaturalKeyAnchor.objects.all(),
        indent=2,
        use_natural_foreign_keys=True,
        use_natural_primary_keys=True,
    )

    # Delete one book (to prove that the natural key generation will only
    # restore the primary keys of books found in the database via the
    # get_natural_key manager method).
    james.delete()

    # Deserialize and test.
    books = list(serializers.deserialize(format, string_data))
    self.assertCountEqual(
        [(book.object.title, book.object.pk) for book in books],
        [
            (book1["title"], adrian.pk),
            (book2["title"], None),
        ],
    )


def natural_pk_mti_test(self, format):
    """
    If serializing objects in a multi-table inheritance relationship using
    natural primary keys, the natural foreign key for the parent is output in
    the fields of the child so it's possible to relate the child to the parent
    when deserializing.
    """
    child_1 = Child.objects.create(parent_data="1", child_data="1")
    child_2 = Child.objects.create(parent_data="2", child_data="2")
    string_data = serializers.serialize(
        format,
        [child_1.parent_ptr, child_2.parent_ptr, child_2, child_1],
        use_natural_foreign_keys=True,
        use_natural_primary_keys=True,
    )
    child_1.delete()
    child_2.delete()
    for obj in serializers.deserialize(format, string_data):
        obj.save()
    children = Child.objects.all()
    self.assertEqual(len(children), 2)
    for child in children:
        # If it's possible to find the superclass from the subclass and it's
        # the correct superclass, it's working.
        self.assertEqual(child.child_data, child.parent_data)


def forward_ref_fk_test(self, format):
    t1 = NaturalKeyThing.objects.create(key="t1")
    t2 = NaturalKeyThing.objects.create(key="t2", other_thing=t1)
    t1.other_thing = t2
    t1.save()
    string_data = serializers.serialize(
        format,
        [t1, t2],
        use_natural_primary_keys=True,
        use_natural_foreign_keys=True,
    )
    NaturalKeyThing.objects.all().delete()
    objs_with_deferred_fields = []
    for obj in serializers.deserialize(
        format, string_data, handle_forward_references=True
    ):
        obj.save()
        if obj.deferred_fields:
            objs_with_deferred_fields.append(obj)
    for obj in objs_with_deferred_fields:
        obj.save_deferred_fields()
    t1 = NaturalKeyThing.objects.get(key="t1")
    t2 = NaturalKeyThing.objects.get(key="t2")
    self.assertEqual(t1.other_thing, t2)
    self.assertEqual(t2.other_thing, t1)


def forward_ref_fk_with_error_test(self, format):
    t1 = NaturalKeyThing.objects.create(key="t1")
    t2 = NaturalKeyThing.objects.create(key="t2", other_thing=t1)
    t1.other_thing = t2
    t1.save()
    string_data = serializers.serialize(
        format,
        [t1],
        use_natural_primary_keys=True,
        use_natural_foreign_keys=True,
    )
    NaturalKeyThing.objects.all().delete()
    objs_with_deferred_fields = []
    for obj in serializers.deserialize(
        format, string_data, handle_forward_references=True
    ):
        obj.save()
        if obj.deferred_fields:
            objs_with_deferred_fields.append(obj)
    obj = objs_with_deferred_fields[0]
    msg = "NaturalKeyThing matching query does not exist"
    with self.assertRaisesMessage(serializers.base.DeserializationError, msg):
        obj.save_deferred_fields()


def forward_ref_m2m_test(self, format):
    t1 = NaturalKeyThing.objects.create(key="t1")
    t2 = NaturalKeyThing.objects.create(key="t2")
    t3 = NaturalKeyThing.objects.create(key="t3")
    t1.other_things.set([t2, t3])
    string_data = serializers.serialize(
        format,
        [t1, t2, t3],
        use_natural_primary_keys=True,
        use_natural_foreign_keys=True,
    )
    NaturalKeyThing.objects.all().delete()
    objs_with_deferred_fields = []
    for obj in serializers.deserialize(
        format, string_data, handle_forward_references=True
    ):
        obj.save()
        if obj.deferred_fields:
            objs_with_deferred_fields.append(obj)
    for obj in objs_with_deferred_fields:
        obj.save_deferred_fields()
    t1 = NaturalKeyThing.objects.get(key="t1")
    t2 = NaturalKeyThing.objects.get(key="t2")
    t3 = NaturalKeyThing.objects.get(key="t3")
    self.assertCountEqual(t1.other_things.all(), [t2, t3])


def forward_ref_m2m_with_error_test(self, format):
    t1 = NaturalKeyThing.objects.create(key="t1")
    t2 = NaturalKeyThing.objects.create(key="t2")
    t3 = NaturalKeyThing.objects.create(key="t3")
    t1.other_things.set([t2, t3])
    t1.save()
    string_data = serializers.serialize(
        format,
        [t1, t2],
        use_natural_primary_keys=True,
        use_natural_foreign_keys=True,
    )
    NaturalKeyThing.objects.all().delete()
    objs_with_deferred_fields = []
    for obj in serializers.deserialize(
        format, string_data, handle_forward_references=True
    ):
        obj.save()
        if obj.deferred_fields:
            objs_with_deferred_fields.append(obj)
    obj = objs_with_deferred_fields[0]
    msg = "NaturalKeyThing matching query does not exist"
    with self.assertRaisesMessage(serializers.base.DeserializationError, msg):
        obj.save_deferred_fields()


def pk_with_default(self, format):
    """
    The deserializer works with natural keys when the primary key has a default
    value.
    """
    obj = NaturalPKWithDefault.objects.create(name="name")
    string_data = serializers.serialize(
        format,
        NaturalPKWithDefault.objects.all(),
        use_natural_foreign_keys=True,
        use_natural_primary_keys=True,
    )
    objs = list(serializers.deserialize(format, string_data))
    self.assertEqual(len(objs), 1)
    self.assertEqual(objs[0].object.pk, obj.pk)


def fk_as_pk_natural_key_not_called(self, format):
    """
    The deserializer doesn't rely on natural keys when a model has a custom
    primary key that is a ForeignKey.
    """
    o1 = NaturalKeyAnchor.objects.create(data="978-1590599969")
    o2 = FKAsPKNoNaturalKey.objects.create(pk_fk=o1)
    serialized_data = serializers.serialize(format, [o1, o2])
    deserialized_objects = list(serializers.deserialize(format, serialized_data))
    self.assertEqual(len(deserialized_objects), 2)
    for obj in deserialized_objects:
        self.assertEqual(obj.object.pk, o1.pk)


# Dynamically register tests for each serializer
register_tests(
    NaturalKeySerializerTests,
    "test_%s_natural_key_serializer",
    natural_key_serializer_test,
)
register_tests(
    NaturalKeySerializerTests, "test_%s_serializer_natural_keys", natural_key_test
)
register_tests(
    NaturalKeySerializerTests, "test_%s_serializer_natural_pks_mti", natural_pk_mti_test
)
register_tests(
    NaturalKeySerializerTests, "test_%s_forward_references_fks", forward_ref_fk_test
)
register_tests(
    NaturalKeySerializerTests,
    "test_%s_forward_references_fk_errors",
    forward_ref_fk_with_error_test,
)
register_tests(
    NaturalKeySerializerTests, "test_%s_forward_references_m2ms", forward_ref_m2m_test
)
register_tests(
    NaturalKeySerializerTests,
    "test_%s_forward_references_m2m_errors",
    forward_ref_m2m_with_error_test,
)
register_tests(NaturalKeySerializerTests, "test_%s_pk_with_default", pk_with_default)
register_tests(
    NaturalKeySerializerTests,
    "test_%s_fk_as_pk_natural_key_not_called",
    fk_as_pk_natural_key_not_called,
)