Debian Codegraph @

src/polymorphic/tests/test_serialization.py

raw
1 """
2 Tests for serialization and dumpdata functionality.
3
4 This module tests that polymorphic models are correctly serialized using Django's
5 dumpdata command, both via call_command and subprocess invocation.
6
7 Regression test for issue #146 - ensuring dumpdata works correctly with polymorphic
8 models.
9 """
10
11 import json
12 import os
13 import pytest
14 import tempfile
15 import subprocess
16 import sys
17 from io import StringIO
18 from pathlib import Path
19
20 from django.conf import settings
21 from django.core.management import call_command
22 from django.db import connections
23
24 from polymorphic.tests.models import (
25 Model2A,
26 Model2B,
27 Model2C,
28 Model2BFiltered,
29 Model2CFiltered,
30 RelatingModel,
31 NatKeyParent,
32 NatKeyChild,
33 )
34 from .utils import is_sqlite_in_memory, is_oracle, get_subprocess_test_db_env
35
36 manage_py = Path(__file__).parent.parent.parent.parent / "manage.py"
37 assert manage_py.exists()
38
39
40 def call_dumpdata(*models, natural_foreign=True, natural_primary=True, all=False):
41 out = StringIO()
42 call_command(
43 "dumpdata",
44 *models,
45 format="json",
46 stdout=out,
47 natural_foreign=natural_foreign,
48 natural_primary=natural_primary,
49 all=all,
50 )
51 return json.loads(out.getvalue())
52
53
54 def run_dumpdata(*models, natural_foreign=True, natural_primary=True, all=False):
55 cmd = [sys.executable, manage_py, "dumpdata", *models, "--format=json"]
56 if natural_foreign:
57 cmd.append("--natural-foreign")
58 if all:
59 cmd.append("--all")
60 if natural_primary:
61 cmd.append("--natural-primary")
62 result = subprocess.run(cmd, capture_output=True, env=get_subprocess_test_db_env())
63 assert result.returncode == 0, result.stderr or result.stdout
64 return json.loads(result.stdout)
65
66
67 @pytest.fixture
68 def dump_objects(db):
69 return (
70 Model2A.objects.create(field1="A1"),
71 Model2B.objects.create(field1="B1", field2="B2"),
72 Model2C.objects.create(field1="C1", field2="C2", field3="C3"),
73 Model2BFiltered.objects.create(field1="BF1", field2="BF2"),
74 Model2CFiltered.objects.create(field1="cf1", field2="cf2", field3="cf3"),
75 Model2CFiltered.objects.create(field1="CF1", field2="CF2", field3="CF3"),
76 )
77
78
79 @pytest.fixture
80 def natkey_dump_objects(db):
81 """
82 Create a small graph of NatKeyParent / NatKeyChild instances.
83
84 Returns:
85 tuple[list[NatKeyParent], list[NatKeyChild]]
86 """
87 return [
88 NatKeyChild.objects.create(slug=f"slug-{i}", content=f"content {i}", val=i)
89 for i in range(5)
90 ]
91
92
93 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
94 @pytest.mark.parametrize(
95 "dumpdata",
96 [
97 pytest.param(call_dumpdata, id="call_command"),
98 pytest.param(
99 run_dumpdata,
100 id="manage",
101 marks=pytest.mark.skipif(
102 is_sqlite_in_memory(),
103 reason="Subprocess test disabled for in-memory sqlite test runs",
104 ),
105 ),
106 ],
107 )
108 @pytest.mark.parametrize("all", [False, True])
109 def test_dumpdata_returns_base_objects_not_downcasted(dumpdata, dump_objects, all):
110 """
111 Test that dumpdata serializes base table rows without polymorphic downcasting.
112
113 When querying Model2A table directly, we should get 3 rows
114 (A, B, C base objects).
115 """
116 # Should have only Model2As
117 assert dumpdata("tests.Model2A", all=all) == [
118 {
119 "fields": {"field1": "A1", "polymorphic_ctype": ["tests", "model2a"]},
120 "model": "tests.model2a",
121 "pk": dump_objects[0].pk,
122 },
123 {
124 "fields": {"field1": "B1", "polymorphic_ctype": ["tests", "model2b"]},
125 "model": "tests.model2a",
126 "pk": dump_objects[1].pk,
127 },
128 {
129 "fields": {"field1": "C1", "polymorphic_ctype": ["tests", "model2c"]},
130 "model": "tests.model2a",
131 "pk": dump_objects[2].pk,
132 },
133 {
134 "fields": {"field1": "BF1", "polymorphic_ctype": ["tests", "model2bfiltered"]},
135 "model": "tests.model2a",
136 "pk": dump_objects[3].pk,
137 },
138 {
139 "fields": {"field1": "cf1", "polymorphic_ctype": ["tests", "model2cfiltered"]},
140 "model": "tests.model2a",
141 "pk": dump_objects[4].pk,
142 },
143 {
144 "fields": {"field1": "CF1", "polymorphic_ctype": ["tests", "model2cfiltered"]},
145 "model": "tests.model2a",
146 "pk": dump_objects[5].pk,
147 },
148 ]
149
150
151 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
152 @pytest.mark.parametrize(
153 "dumpdata",
154 [
155 pytest.param(call_dumpdata, id="call_command"),
156 pytest.param(
157 run_dumpdata,
158 id="manage",
159 marks=pytest.mark.skipif(
160 is_sqlite_in_memory() or is_oracle(),
161 reason="Subprocess test disabled for in-memory sqlite test runs",
162 ),
163 ),
164 ],
165 )
166 @pytest.mark.parametrize("all", [False, True], ids=["default", "all"])
167 def test_dumpdata_all_flag(dumpdata, dump_objects, all):
168 """Test dumping only a child model works correctly."""
169
170 expected = [
171 *(
172 [
173 {
174 "fields": {"model2b_ptr": dump_objects[3].pk},
175 "model": "tests.model2bfiltered",
176 "pk": dump_objects[3].pk,
177 }
178 ]
179 if all
180 else []
181 ),
182 {
183 "fields": {"model2b_ptr": dump_objects[4].pk},
184 "model": "tests.model2bfiltered",
185 "pk": dump_objects[4].pk,
186 },
187 *(
188 [
189 {
190 "fields": {"model2b_ptr": dump_objects[5].pk},
191 "model": "tests.model2bfiltered",
192 "pk": dump_objects[5].pk,
193 }
194 ]
195 if all
196 else []
197 ),
198 {
199 "fields": {"field3": "cf3", "model2bfiltered_ptr": dump_objects[4].pk},
200 "model": "tests.model2cfiltered",
201 "pk": dump_objects[4].pk,
202 },
203 *(
204 [
205 {
206 "fields": {"field3": "CF3", "model2bfiltered_ptr": dump_objects[5].pk},
207 "model": "tests.model2cfiltered",
208 "pk": dump_objects[5].pk,
209 }
210 ]
211 if all
212 else []
213 ),
214 ]
215 assert dumpdata("tests.Model2BFiltered", "tests.Model2CFiltered", all=all) == expected
216
217
218 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
219 @pytest.mark.parametrize(
220 "dumpdata",
221 [
222 pytest.param(call_dumpdata, id="call_command"),
223 pytest.param(
224 run_dumpdata,
225 id="manage",
226 marks=pytest.mark.skipif(
227 is_sqlite_in_memory() or is_oracle(),
228 reason="Subprocess test disabled for in-memory sqlite test runs",
229 ),
230 ),
231 ],
232 )
233 def test_dumpdata_child_model_only(dumpdata, dump_objects):
234 """Test dumping only a child model works correctly."""
235 assert dumpdata("tests.Model2C") == [
236 {
237 "fields": {
238 "field3": "C3",
239 "model2b_ptr": dump_objects[2].pk,
240 },
241 "model": "tests.model2c",
242 "pk": dump_objects[2].pk,
243 }
244 ]
245
246
247 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
248 @pytest.mark.parametrize(
249 "dumpdata",
250 [
251 pytest.param(call_dumpdata, id="call_command"),
252 pytest.param(
253 run_dumpdata,
254 id="manage",
255 marks=pytest.mark.skipif(
256 is_sqlite_in_memory() or is_oracle(),
257 reason="Subprocess test disabled for in-memory sqlite test runs",
258 ),
259 ),
260 ],
261 )
262 @pytest.mark.parametrize("all", [False, True], ids=["default", "all"])
263 def test_dumpdata_multi_table_roundtrip(dumpdata, dump_objects, all):
264 data = dumpdata(
265 "tests.Model2A",
266 "tests.Model2B",
267 "tests.Model2C",
268 "tests.Model2BFiltered",
269 "tests.Model2CFiltered",
270 all=all,
271 )
272
273 # When dumping Model2A (the parent model), ALL instances are returned regardless of
274 # the `all` parameter, because Model2A doesn't have a filtered manager.
275 # The `all` parameter only affects behavior when dumping child models WITHOUT their parent.
276 expected = [
277 {
278 "fields": {"field1": "A1", "polymorphic_ctype": ["tests", "model2a"]},
279 "model": "tests.model2a",
280 "pk": dump_objects[0].pk,
281 },
282 {
283 "fields": {"field1": "B1", "polymorphic_ctype": ["tests", "model2b"]},
284 "model": "tests.model2a",
285 "pk": dump_objects[1].pk,
286 },
287 {
288 "fields": {"field1": "C1", "polymorphic_ctype": ["tests", "model2c"]},
289 "model": "tests.model2a",
290 "pk": dump_objects[2].pk,
291 },
292 {
293 "fields": {"field1": "BF1", "polymorphic_ctype": ["tests", "model2bfiltered"]},
294 "model": "tests.model2a",
295 "pk": dump_objects[3].pk,
296 },
297 {
298 "fields": {"field1": "cf1", "polymorphic_ctype": ["tests", "model2cfiltered"]},
299 "model": "tests.model2a",
300 "pk": dump_objects[4].pk,
301 },
302 {
303 "fields": {"field1": "CF1", "polymorphic_ctype": ["tests", "model2cfiltered"]},
304 "model": "tests.model2a",
305 "pk": dump_objects[5].pk,
306 },
307 {
308 "fields": {"field2": "B2", "model2a_ptr": dump_objects[1].pk},
309 "model": "tests.model2b",
310 "pk": dump_objects[1].pk,
311 },
312 {
313 "fields": {"field2": "C2", "model2a_ptr": dump_objects[2].pk},
314 "model": "tests.model2b",
315 "pk": dump_objects[2].pk,
316 },
317 {
318 "fields": {"field2": "BF2", "model2a_ptr": dump_objects[3].pk},
319 "model": "tests.model2b",
320 "pk": dump_objects[3].pk,
321 },
322 {
323 "fields": {"field2": "cf2", "model2a_ptr": dump_objects[4].pk},
324 "model": "tests.model2b",
325 "pk": dump_objects[4].pk,
326 },
327 {
328 "fields": {"field2": "CF2", "model2a_ptr": dump_objects[5].pk},
329 "model": "tests.model2b",
330 "pk": dump_objects[5].pk,
331 },
332 {
333 "fields": {"field3": "C3", "model2b_ptr": dump_objects[2].pk},
334 "model": "tests.model2c",
335 "pk": dump_objects[2].pk,
336 },
337 *(
338 [
339 {
340 "fields": {"model2b_ptr": dump_objects[3].pk},
341 "model": "tests.model2bfiltered",
342 "pk": dump_objects[3].pk,
343 }
344 ]
345 if all
346 else []
347 ),
348 {
349 "fields": {"model2b_ptr": dump_objects[4].pk},
350 "model": "tests.model2bfiltered",
351 "pk": dump_objects[4].pk,
352 },
353 *(
354 [
355 {
356 "fields": {"model2b_ptr": dump_objects[5].pk},
357 "model": "tests.model2bfiltered",
358 "pk": dump_objects[5].pk,
359 }
360 ]
361 if all
362 else []
363 ),
364 {
365 "fields": {"field3": "cf3", "model2bfiltered_ptr": dump_objects[4].pk},
366 "model": "tests.model2cfiltered",
367 "pk": dump_objects[4].pk,
368 },
369 *(
370 [
371 {
372 "fields": {"field3": "CF3", "model2bfiltered_ptr": dump_objects[5].pk},
373 "model": "tests.model2cfiltered",
374 "pk": dump_objects[5].pk,
375 }
376 ]
377 if all
378 else []
379 ),
380 ]
381
382 assert data == expected
383
384 Model2A.objects.all().delete()
385
386 with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
387 f.write(json.dumps(data))
388 fixture_file = f.name
389
390 try:
391 call_command("loaddata", fixture_file, verbosity=0)
392
393 # After loaddata, all 6 objects are loaded
394 assert Model2A.objects.count() == 6
395 assert Model2B.objects.count() == 5
396 assert Model2C.objects.count() == 1
397 # Filtered managers still apply, so only cf1 passes the filter
398 assert Model2BFiltered.objects.count() == 1
399 assert Model2CFiltered.objects.count() == 1
400
401 model2a_objects = list(Model2A.objects.order_by("pk"))
402 a, b, c, bf, cf_lower, cf_upper = model2a_objects
403
404 assert a.__class__ == Model2A
405 assert b.__class__ == Model2B
406 assert c.__class__ == Model2C
407 assert cf_lower.__class__ == Model2CFiltered
408
409 if all:
410 assert bf.__class__ == Model2BFiltered
411 assert cf_upper.__class__ == Model2CFiltered
412 else:
413 # the parent class wasnt filtered so these should have been upcasted
414 assert bf.__class__ == Model2B
415 assert cf_upper.__class__ == Model2B
416
417 assert a.field1 == "A1"
418 assert b.field1 == "B1"
419 assert b.field2 == "B2"
420 assert c.field1 == "C1"
421 assert c.field2 == "C2"
422 assert c.field3 == "C3"
423 assert cf_lower.field1 == "cf1"
424 assert cf_lower.field2 == "cf2"
425 assert cf_lower.field3 == "cf3"
426
427 if all:
428 assert bf.field1 == "BF1"
429 assert bf.field2 == "BF2"
430 assert cf_upper.field1 == "CF1"
431 assert cf_upper.field2 == "CF2"
432 assert cf_upper.field3 == "CF3"
433 else:
434 assert bf.field1 == "BF1"
435 assert bf.field2 == "BF2"
436 # cf_upper is now a Model2B, so field3 does not exist
437 assert cf_upper.field1 == "CF1"
438 assert cf_upper.field2 == "CF2"
439 assert not hasattr(cf_upper, "field3")
440
441 finally:
442 # Clean up temporary file
443 os.unlink(fixture_file)
444
445
446 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
447 @pytest.mark.parametrize(
448 "dumpdata",
449 [
450 pytest.param(call_dumpdata, id="call_command"),
451 pytest.param(
452 run_dumpdata,
453 id="manage",
454 marks=pytest.mark.skipif(
455 is_sqlite_in_memory() or is_oracle(),
456 reason="Subprocess test disabled for in-memory sqlite test runs",
457 ),
458 ),
459 ],
460 )
461 @pytest.mark.parametrize("all", [False, True], ids=["default", "all"])
462 def test_dumpdata_related_polymorphic_roundtrip(dumpdata, dump_objects, all):
463 rm1 = RelatingModel.objects.create()
464 rm2 = RelatingModel.objects.create()
465 rm3 = RelatingModel.objects.create()
466 rm1.many2many.add(dump_objects[0])
467 rm2.many2many.add(dump_objects[1], dump_objects[2])
468 # Add all filtered models to rm3
469 rm3.many2many.add(dump_objects[3], dump_objects[4], dump_objects[5])
470
471 data = dumpdata(
472 "tests.Model2A",
473 "tests.Model2B",
474 "tests.Model2C",
475 "tests.Model2BFiltered",
476 "tests.Model2CFiltered",
477 "tests.RelatingModel",
478 natural_foreign=True,
479 natural_primary=False,
480 all=all,
481 )
482
483 Model2A.objects.all().delete()
484 RelatingModel.objects.all().delete()
485
486 with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
487 f.write(json.dumps(data))
488 fixture_file = f.name
489
490 try:
491 call_command("loaddata", fixture_file, verbosity=0)
492
493 # After loaddata, all 6 objects are loaded
494 assert Model2A.objects.count() == 6
495 assert Model2B.objects.count() == 5
496 assert Model2C.objects.count() == 1
497 # Filtered managers still apply, so only cf1 passes the filter
498 assert Model2BFiltered.objects.count() == 1
499 assert Model2BFiltered._base_manager.count() == (3 if all else 1)
500 assert Model2CFiltered.objects.count() == 1
501 assert Model2CFiltered._base_manager.count() == (2 if all else 1)
502
503 model2a_objects = Model2A.objects.order_by("pk")
504 a, b, c, bf, cf_lower, cf_upper = model2a_objects.all()
505
506 assert a.__class__ == Model2A
507 assert b.__class__ == Model2B
508 assert c.__class__ == Model2C
509 assert cf_lower.__class__ == Model2CFiltered
510
511 if all:
512 assert bf.__class__ == Model2BFiltered
513 assert cf_upper.__class__ == Model2CFiltered
514 else:
515 # the parent class wasnt filtered so these should have been upcasted
516 assert bf.__class__ == Model2B
517 assert cf_upper.__class__ == Model2B
518
519 assert a.field1 == "A1"
520 assert b.field1 == "B1"
521 assert b.field2 == "B2"
522 assert c.field1 == "C1"
523 assert c.field2 == "C2"
524 assert c.field3 == "C3"
525 assert cf_lower.field1 == "cf1"
526 assert cf_lower.field2 == "cf2"
527 assert cf_lower.field3 == "cf3"
528
529 if all:
530 assert bf.field1 == "BF1"
531 assert bf.field2 == "BF2"
532 assert cf_upper.field1 == "CF1"
533 assert cf_upper.field2 == "CF2"
534 assert cf_upper.field3 == "CF3"
535 else:
536 assert bf.field1 == "BF1"
537 assert bf.field2 == "BF2"
538 # cf_upper is now a Model2B, so field3 does not exist
539 assert cf_upper.field1 == "CF1"
540 assert cf_upper.field2 == "CF2"
541 assert not hasattr(cf_upper, "field3")
542
543 # Verify relationships
544 assert RelatingModel.objects.count() == 3
545 rm_objects = list(RelatingModel.objects.order_by("pk"))
546
547 # rm1 has A
548 assert rm_objects[0].many2many.count() == 1
549 assert rm_objects[0].many2many.first() == a
550
551 # rm2 has B and C
552 assert rm_objects[1].many2many.count() == 2
553 assert set(rm_objects[1].many2many.all()) == {b, c}
554
555 # rm3 has all three filtered models
556 assert rm_objects[2].many2many.count() == 3
557 rm3_related = set(rm_objects[2].many2many.all())
558 assert len(rm3_related) == 3
559 assert bf in rm3_related
560 assert cf_lower in rm3_related
561 assert cf_upper in rm3_related
562
563 finally:
564 # Clean up temporary file
565 os.unlink(fixture_file)
566
567
568 @pytest.mark.django_db(transaction=True, databases=["default", "secondary"])
569 @pytest.mark.parametrize(
570 "dumpdata",
571 [
572 pytest.param(call_dumpdata, id="call_command"),
573 pytest.param(
574 run_dumpdata,
575 id="manage",
576 marks=pytest.mark.skipif(
577 is_sqlite_in_memory() or is_oracle(),
578 reason="Subprocess test disabled for in-memory sqlite test runs",
579 ),
580 ),
581 ],
582 )
583 def test_dumpdata_natural_keys(dumpdata, natkey_dump_objects):
584 data = dumpdata(
585 "tests",
586 natural_foreign=True,
587 natural_primary=True,
588 all=all,
589 )
590
591 assert data == [
592 {
593 "fields": {
594 "content": "content 0",
595 "polymorphic_ctype": ["tests", "natkeychild"],
596 "slug": "slug-0",
597 },
598 "model": "tests.natkeyparent",
599 },
600 {
601 "fields": {
602 "content": "content 1",
603 "polymorphic_ctype": ["tests", "natkeychild"],
604 "slug": "slug-1",
605 },
606 "model": "tests.natkeyparent",
607 },
608 {
609 "fields": {
610 "content": "content 2",
611 "polymorphic_ctype": ["tests", "natkeychild"],
612 "slug": "slug-2",
613 },
614 "model": "tests.natkeyparent",
615 },
616 {
617 "fields": {
618 "content": "content 3",
619 "polymorphic_ctype": ["tests", "natkeychild"],
620 "slug": "slug-3",
621 },
622 "model": "tests.natkeyparent",
623 },
624 {
625 "fields": {
626 "content": "content 4",
627 "polymorphic_ctype": ["tests", "natkeychild"],
628 "slug": "slug-4",
629 },
630 "model": "tests.natkeyparent",
631 },
632 {"fields": {"foo": ["slug-0"], "val": 0}, "model": "tests.natkeychild"},
633 {"fields": {"foo": ["slug-1"], "val": 1}, "model": "tests.natkeychild"},
634 {"fields": {"foo": ["slug-2"], "val": 2}, "model": "tests.natkeychild"},
635 {"fields": {"foo": ["slug-3"], "val": 3}, "model": "tests.natkeychild"},
636 {"fields": {"foo": ["slug-4"], "val": 4}, "model": "tests.natkeychild"},
637 ]
638
639 NatKeyChild.objects.all().delete()
640 NatKeyParent.objects.all().delete()
641
642 with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f:
643 f.write(json.dumps(data))
644 fixture_file = f.name
645
646 try:
647 call_command("loaddata", fixture_file, verbosity=0)
648
649 for old, new in zip(
650 natkey_dump_objects,
651 NatKeyParent.objects.order_by("pk").all(),
652 ):
653 assert new.__class__ == old.__class__ is NatKeyChild
654 assert new.slug == old.slug
655 assert new.content == old.content
656 assert new.val == old.val
657
658 finally:
659 # Clean up temporary file
660 os.unlink(fixture_file)