1. # Unittests for fixtures.
    
  2. import json
    
  3. import os
    
  4. import re
    
  5. from io import StringIO
    
  6. from pathlib import Path
    
  7. 
    
  8. from django.core import management, serializers
    
  9. from django.core.exceptions import ImproperlyConfigured
    
  10. from django.core.serializers.base import DeserializationError
    
  11. from django.db import IntegrityError, transaction
    
  12. from django.db.models import signals
    
  13. from django.test import (
    
  14.     TestCase,
    
  15.     TransactionTestCase,
    
  16.     override_settings,
    
  17.     skipIfDBFeature,
    
  18.     skipUnlessDBFeature,
    
  19. )
    
  20. 
    
  21. from .models import (
    
  22.     Absolute,
    
  23.     Animal,
    
  24.     Article,
    
  25.     Book,
    
  26.     Child,
    
  27.     Circle1,
    
  28.     Circle2,
    
  29.     Circle3,
    
  30.     ExternalDependency,
    
  31.     M2MCircular1ThroughAB,
    
  32.     M2MCircular1ThroughBC,
    
  33.     M2MCircular1ThroughCA,
    
  34.     M2MCircular2ThroughAB,
    
  35.     M2MComplexA,
    
  36.     M2MComplexB,
    
  37.     M2MComplexCircular1A,
    
  38.     M2MComplexCircular1B,
    
  39.     M2MComplexCircular1C,
    
  40.     M2MComplexCircular2A,
    
  41.     M2MComplexCircular2B,
    
  42.     M2MSimpleA,
    
  43.     M2MSimpleB,
    
  44.     M2MSimpleCircularA,
    
  45.     M2MSimpleCircularB,
    
  46.     M2MThroughAB,
    
  47.     NaturalKeyWithFKDependency,
    
  48.     NKChild,
    
  49.     Parent,
    
  50.     Person,
    
  51.     RefToNKChild,
    
  52.     Store,
    
  53.     Stuff,
    
  54.     Thingy,
    
  55.     Widget,
    
  56. )
    
  57. 
    
  58. _cur_dir = os.path.dirname(os.path.abspath(__file__))
    
  59. 
    
  60. 
    
  61. class TestFixtures(TestCase):
    
  62.     def animal_pre_save_check(self, signal, sender, instance, **kwargs):
    
  63.         self.pre_save_checks.append(
    
  64.             (
    
  65.                 "Count = %s (%s)" % (instance.count, type(instance.count)),
    
  66.                 "Weight = %s (%s)" % (instance.weight, type(instance.weight)),
    
  67.             )
    
  68.         )
    
  69. 
    
  70.     def test_duplicate_pk(self):
    
  71.         """
    
  72.         This is a regression test for ticket #3790.
    
  73.         """
    
  74.         # Load a fixture that uses PK=1
    
  75.         management.call_command(
    
  76.             "loaddata",
    
  77.             "sequence",
    
  78.             verbosity=0,
    
  79.         )
    
  80. 
    
  81.         # Create a new animal. Without a sequence reset, this new object
    
  82.         # will take a PK of 1 (on Postgres), and the save will fail.
    
  83. 
    
  84.         animal = Animal(
    
  85.             name="Platypus",
    
  86.             latin_name="Ornithorhynchus anatinus",
    
  87.             count=2,
    
  88.             weight=2.2,
    
  89.         )
    
  90.         animal.save()
    
  91.         self.assertGreater(animal.id, 1)
    
  92. 
    
  93.     def test_loaddata_not_found_fields_not_ignore(self):
    
  94.         """
    
  95.         Test for ticket #9279 -- Error is raised for entries in
    
  96.         the serialized data for fields that have been removed
    
  97.         from the database when not ignored.
    
  98.         """
    
  99.         with self.assertRaises(DeserializationError):
    
  100.             management.call_command(
    
  101.                 "loaddata",
    
  102.                 "sequence_extra",
    
  103.                 verbosity=0,
    
  104.             )
    
  105. 
    
  106.     def test_loaddata_not_found_fields_ignore(self):
    
  107.         """
    
  108.         Test for ticket #9279 -- Ignores entries in
    
  109.         the serialized data for fields that have been removed
    
  110.         from the database.
    
  111.         """
    
  112.         management.call_command(
    
  113.             "loaddata",
    
  114.             "sequence_extra",
    
  115.             ignore=True,
    
  116.             verbosity=0,
    
  117.         )
    
  118.         self.assertEqual(Animal.specimens.all()[0].name, "Lion")
    
  119. 
    
  120.     def test_loaddata_not_found_fields_ignore_xml(self):
    
  121.         """
    
  122.         Test for ticket #19998 -- Ignore entries in the XML serialized data
    
  123.         for fields that have been removed from the model definition.
    
  124.         """
    
  125.         management.call_command(
    
  126.             "loaddata",
    
  127.             "sequence_extra_xml",
    
  128.             ignore=True,
    
  129.             verbosity=0,
    
  130.         )
    
  131.         self.assertEqual(Animal.specimens.all()[0].name, "Wolf")
    
  132. 
    
  133.     @skipIfDBFeature("interprets_empty_strings_as_nulls")
    
  134.     def test_pretty_print_xml(self):
    
  135.         """
    
  136.         Regression test for ticket #4558 -- pretty printing of XML fixtures
    
  137.         doesn't affect parsing of None values.
    
  138.         """
    
  139.         # Load a pretty-printed XML fixture with Nulls.
    
  140.         management.call_command(
    
  141.             "loaddata",
    
  142.             "pretty.xml",
    
  143.             verbosity=0,
    
  144.         )
    
  145.         self.assertIsNone(Stuff.objects.all()[0].name)
    
  146.         self.assertIsNone(Stuff.objects.all()[0].owner)
    
  147. 
    
  148.     @skipUnlessDBFeature("interprets_empty_strings_as_nulls")
    
  149.     def test_pretty_print_xml_empty_strings(self):
    
  150.         """
    
  151.         Regression test for ticket #4558 -- pretty printing of XML fixtures
    
  152.         doesn't affect parsing of None values.
    
  153.         """
    
  154.         # Load a pretty-printed XML fixture with Nulls.
    
  155.         management.call_command(
    
  156.             "loaddata",
    
  157.             "pretty.xml",
    
  158.             verbosity=0,
    
  159.         )
    
  160.         self.assertEqual(Stuff.objects.all()[0].name, "")
    
  161.         self.assertIsNone(Stuff.objects.all()[0].owner)
    
  162. 
    
  163.     def test_absolute_path(self):
    
  164.         """
    
  165.         Regression test for ticket #6436 --
    
  166.         os.path.join will throw away the initial parts of a path if it
    
  167.         encounters an absolute path.
    
  168.         This means that if a fixture is specified as an absolute path,
    
  169.         we need to make sure we don't discover the absolute path in every
    
  170.         fixture directory.
    
  171.         """
    
  172.         load_absolute_path = os.path.join(
    
  173.             os.path.dirname(__file__), "fixtures", "absolute.json"
    
  174.         )
    
  175.         management.call_command(
    
  176.             "loaddata",
    
  177.             load_absolute_path,
    
  178.             verbosity=0,
    
  179.         )
    
  180.         self.assertEqual(Absolute.objects.count(), 1)
    
  181. 
    
  182.     def test_relative_path(self, path=["fixtures", "absolute.json"]):
    
  183.         relative_path = os.path.join(*path)
    
  184.         cwd = os.getcwd()
    
  185.         try:
    
  186.             os.chdir(_cur_dir)
    
  187.             management.call_command(
    
  188.                 "loaddata",
    
  189.                 relative_path,
    
  190.                 verbosity=0,
    
  191.             )
    
  192.         finally:
    
  193.             os.chdir(cwd)
    
  194.         self.assertEqual(Absolute.objects.count(), 1)
    
  195. 
    
  196.     @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures_1")])
    
  197.     def test_relative_path_in_fixture_dirs(self):
    
  198.         self.test_relative_path(path=["inner", "absolute.json"])
    
  199. 
    
  200.     def test_path_containing_dots(self):
    
  201.         management.call_command(
    
  202.             "loaddata",
    
  203.             "path.containing.dots.json",
    
  204.             verbosity=0,
    
  205.         )
    
  206.         self.assertEqual(Absolute.objects.count(), 1)
    
  207. 
    
  208.     def test_unknown_format(self):
    
  209.         """
    
  210.         Test for ticket #4371 -- Loading data of an unknown format should fail
    
  211.         Validate that error conditions are caught correctly
    
  212.         """
    
  213.         msg = (
    
  214.             "Problem installing fixture 'bad_fix.ture1': unkn is not a known "
    
  215.             "serialization format."
    
  216.         )
    
  217.         with self.assertRaisesMessage(management.CommandError, msg):
    
  218.             management.call_command(
    
  219.                 "loaddata",
    
  220.                 "bad_fix.ture1.unkn",
    
  221.                 verbosity=0,
    
  222.             )
    
  223. 
    
  224.     @override_settings(SERIALIZATION_MODULES={"unkn": "unexistent.path"})
    
  225.     def test_unimportable_serializer(self):
    
  226.         """
    
  227.         Failing serializer import raises the proper error
    
  228.         """
    
  229.         with self.assertRaisesMessage(ImportError, "No module named 'unexistent'"):
    
  230.             management.call_command(
    
  231.                 "loaddata",
    
  232.                 "bad_fix.ture1.unkn",
    
  233.                 verbosity=0,
    
  234.             )
    
  235. 
    
  236.     def test_invalid_data(self):
    
  237.         """
    
  238.         Test for ticket #4371 -- Loading a fixture file with invalid data
    
  239.         using explicit filename.
    
  240.         Test for ticket #18213 -- warning conditions are caught correctly
    
  241.         """
    
  242.         msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
    
  243.         with self.assertWarnsMessage(RuntimeWarning, msg):
    
  244.             management.call_command(
    
  245.                 "loaddata",
    
  246.                 "bad_fixture2.xml",
    
  247.                 verbosity=0,
    
  248.             )
    
  249. 
    
  250.     def test_invalid_data_no_ext(self):
    
  251.         """
    
  252.         Test for ticket #4371 -- Loading a fixture file with invalid data
    
  253.         without file extension.
    
  254.         Test for ticket #18213 -- warning conditions are caught correctly
    
  255.         """
    
  256.         msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
    
  257.         with self.assertWarnsMessage(RuntimeWarning, msg):
    
  258.             management.call_command(
    
  259.                 "loaddata",
    
  260.                 "bad_fixture2",
    
  261.                 verbosity=0,
    
  262.             )
    
  263. 
    
  264.     def test_empty(self):
    
  265.         """
    
  266.         Test for ticket #18213 -- Loading a fixture file with no data output a warning.
    
  267.         Previously empty fixture raises an error exception, see ticket #4371.
    
  268.         """
    
  269.         msg = "No fixture data found for 'empty'. (File format may be invalid.)"
    
  270.         with self.assertWarnsMessage(RuntimeWarning, msg):
    
  271.             management.call_command(
    
  272.                 "loaddata",
    
  273.                 "empty",
    
  274.                 verbosity=0,
    
  275.             )
    
  276. 
    
  277.     def test_error_message(self):
    
  278.         """
    
  279.         Regression for #9011 - error message is correct.
    
  280.         Change from error to warning for ticket #18213.
    
  281.         """
    
  282.         msg = "No fixture data found for 'bad_fixture2'. (File format may be invalid.)"
    
  283.         with self.assertWarnsMessage(RuntimeWarning, msg):
    
  284.             management.call_command(
    
  285.                 "loaddata",
    
  286.                 "bad_fixture2",
    
  287.                 "animal",
    
  288.                 verbosity=0,
    
  289.             )
    
  290. 
    
  291.     def test_pg_sequence_resetting_checks(self):
    
  292.         """
    
  293.         Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't
    
  294.         ascend to parent models when inheritance is used
    
  295.         (since they are treated individually).
    
  296.         """
    
  297.         management.call_command(
    
  298.             "loaddata",
    
  299.             "model-inheritance.json",
    
  300.             verbosity=0,
    
  301.         )
    
  302.         self.assertEqual(Parent.objects.all()[0].id, 1)
    
  303.         self.assertEqual(Child.objects.all()[0].id, 1)
    
  304. 
    
  305.     def test_close_connection_after_loaddata(self):
    
  306.         """
    
  307.         Test for ticket #7572 -- MySQL has a problem if the same connection is
    
  308.         used to create tables, load data, and then query over that data.
    
  309.         To compensate, we close the connection after running loaddata.
    
  310.         This ensures that a new connection is opened when test queries are
    
  311.         issued.
    
  312.         """
    
  313.         management.call_command(
    
  314.             "loaddata",
    
  315.             "big-fixture.json",
    
  316.             verbosity=0,
    
  317.         )
    
  318.         articles = Article.objects.exclude(id=9)
    
  319.         self.assertEqual(
    
  320.             list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
    
  321.         )
    
  322.         # Just for good measure, run the same query again.
    
  323.         # Under the influence of ticket #7572, this will
    
  324.         # give a different result to the previous call.
    
  325.         self.assertEqual(
    
  326.             list(articles.values_list("id", flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]
    
  327.         )
    
  328. 
    
  329.     def test_field_value_coerce(self):
    
  330.         """
    
  331.         Test for tickets #8298, #9942 - Field values should be coerced into the
    
  332.         correct type by the deserializer, not as part of the database write.
    
  333.         """
    
  334.         self.pre_save_checks = []
    
  335.         signals.pre_save.connect(self.animal_pre_save_check)
    
  336.         try:
    
  337.             management.call_command(
    
  338.                 "loaddata",
    
  339.                 "animal.xml",
    
  340.                 verbosity=0,
    
  341.             )
    
  342.             self.assertEqual(
    
  343.                 self.pre_save_checks,
    
  344.                 [("Count = 42 (<class 'int'>)", "Weight = 1.2 (<class 'float'>)")],
    
  345.             )
    
  346.         finally:
    
  347.             signals.pre_save.disconnect(self.animal_pre_save_check)
    
  348. 
    
  349.     def test_dumpdata_uses_default_manager(self):
    
  350.         """
    
  351.         Regression for #11286
    
  352.         Dumpdata honors the default manager. Dump the current contents of
    
  353.         the database as a JSON fixture
    
  354.         """
    
  355.         management.call_command(
    
  356.             "loaddata",
    
  357.             "animal.xml",
    
  358.             verbosity=0,
    
  359.         )
    
  360.         management.call_command(
    
  361.             "loaddata",
    
  362.             "sequence.json",
    
  363.             verbosity=0,
    
  364.         )
    
  365.         animal = Animal(
    
  366.             name="Platypus",
    
  367.             latin_name="Ornithorhynchus anatinus",
    
  368.             count=2,
    
  369.             weight=2.2,
    
  370.         )
    
  371.         animal.save()
    
  372. 
    
  373.         out = StringIO()
    
  374.         management.call_command(
    
  375.             "dumpdata",
    
  376.             "fixtures_regress.animal",
    
  377.             format="json",
    
  378.             stdout=out,
    
  379.         )
    
  380. 
    
  381.         # Output order isn't guaranteed, so check for parts
    
  382.         data = out.getvalue()
    
  383. 
    
  384.         # Get rid of artifacts like '000000002' to eliminate the differences
    
  385.         # between different Python versions.
    
  386.         data = re.sub("0{6,}[0-9]", "", data)
    
  387. 
    
  388.         animals_data = sorted(
    
  389.             [
    
  390.                 {
    
  391.                     "pk": 1,
    
  392.                     "model": "fixtures_regress.animal",
    
  393.                     "fields": {
    
  394.                         "count": 3,
    
  395.                         "weight": 1.2,
    
  396.                         "name": "Lion",
    
  397.                         "latin_name": "Panthera leo",
    
  398.                     },
    
  399.                 },
    
  400.                 {
    
  401.                     "pk": 10,
    
  402.                     "model": "fixtures_regress.animal",
    
  403.                     "fields": {
    
  404.                         "count": 42,
    
  405.                         "weight": 1.2,
    
  406.                         "name": "Emu",
    
  407.                         "latin_name": "Dromaius novaehollandiae",
    
  408.                     },
    
  409.                 },
    
  410.                 {
    
  411.                     "pk": animal.pk,
    
  412.                     "model": "fixtures_regress.animal",
    
  413.                     "fields": {
    
  414.                         "count": 2,
    
  415.                         "weight": 2.2,
    
  416.                         "name": "Platypus",
    
  417.                         "latin_name": "Ornithorhynchus anatinus",
    
  418.                     },
    
  419.                 },
    
  420.             ],
    
  421.             key=lambda x: x["pk"],
    
  422.         )
    
  423. 
    
  424.         data = sorted(json.loads(data), key=lambda x: x["pk"])
    
  425. 
    
  426.         self.maxDiff = 1024
    
  427.         self.assertEqual(data, animals_data)
    
  428. 
    
  429.     def test_proxy_model_included(self):
    
  430.         """
    
  431.         Regression for #11428 - Proxy models aren't included when you dumpdata
    
  432.         """
    
  433.         out = StringIO()
    
  434.         # Create an instance of the concrete class
    
  435.         widget = Widget.objects.create(name="grommet")
    
  436.         management.call_command(
    
  437.             "dumpdata",
    
  438.             "fixtures_regress.widget",
    
  439.             "fixtures_regress.widgetproxy",
    
  440.             format="json",
    
  441.             stdout=out,
    
  442.         )
    
  443.         self.assertJSONEqual(
    
  444.             out.getvalue(),
    
  445.             '[{"pk": %d, "model": "fixtures_regress.widget", '
    
  446.             '"fields": {"name": "grommet"}}]' % widget.pk,
    
  447.         )
    
  448. 
    
  449.     @skipUnlessDBFeature("supports_forward_references")
    
  450.     def test_loaddata_works_when_fixture_has_forward_refs(self):
    
  451.         """
    
  452.         Forward references cause fixtures not to load in MySQL (InnoDB).
    
  453.         """
    
  454.         management.call_command(
    
  455.             "loaddata",
    
  456.             "forward_ref.json",
    
  457.             verbosity=0,
    
  458.         )
    
  459.         self.assertEqual(Book.objects.all()[0].id, 1)
    
  460.         self.assertEqual(Person.objects.all()[0].id, 4)
    
  461. 
    
  462.     def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
    
  463.         """
    
  464.         Data with nonexistent child key references raises error.
    
  465.         """
    
  466.         with self.assertRaisesMessage(IntegrityError, "Problem installing fixture"):
    
  467.             management.call_command(
    
  468.                 "loaddata",
    
  469.                 "forward_ref_bad_data.json",
    
  470.                 verbosity=0,
    
  471.             )
    
  472. 
    
  473.     @skipUnlessDBFeature("supports_forward_references")
    
  474.     @override_settings(
    
  475.         FIXTURE_DIRS=[
    
  476.             os.path.join(_cur_dir, "fixtures_1"),
    
  477.             os.path.join(_cur_dir, "fixtures_2"),
    
  478.         ]
    
  479.     )
    
  480.     def test_loaddata_forward_refs_split_fixtures(self):
    
  481.         """
    
  482.         Regression for #17530 - should be able to cope with forward references
    
  483.         when the fixtures are not in the same files or directories.
    
  484.         """
    
  485.         management.call_command(
    
  486.             "loaddata",
    
  487.             "forward_ref_1.json",
    
  488.             "forward_ref_2.json",
    
  489.             verbosity=0,
    
  490.         )
    
  491.         self.assertEqual(Book.objects.all()[0].id, 1)
    
  492.         self.assertEqual(Person.objects.all()[0].id, 4)
    
  493. 
    
  494.     def test_loaddata_no_fixture_specified(self):
    
  495.         """
    
  496.         Error is quickly reported when no fixtures is provided in the command
    
  497.         line.
    
  498.         """
    
  499.         msg = (
    
  500.             "No database fixture specified. Please provide the path of at least one "
    
  501.             "fixture in the command line."
    
  502.         )
    
  503.         with self.assertRaisesMessage(management.CommandError, msg):
    
  504.             management.call_command(
    
  505.                 "loaddata",
    
  506.                 verbosity=0,
    
  507.             )
    
  508. 
    
  509.     def test_ticket_20820(self):
    
  510.         """
    
  511.         Regression for ticket #20820 -- loaddata on a model that inherits
    
  512.         from a model with a M2M shouldn't blow up.
    
  513.         """
    
  514.         management.call_command(
    
  515.             "loaddata",
    
  516.             "special-article.json",
    
  517.             verbosity=0,
    
  518.         )
    
  519. 
    
  520.     def test_ticket_22421(self):
    
  521.         """
    
  522.         Regression for ticket #22421 -- loaddata on a model that inherits from
    
  523.         a grand-parent model with a M2M but via an abstract parent shouldn't
    
  524.         blow up.
    
  525.         """
    
  526.         management.call_command(
    
  527.             "loaddata",
    
  528.             "feature.json",
    
  529.             verbosity=0,
    
  530.         )
    
  531. 
    
  532.     def test_loaddata_with_m2m_to_self(self):
    
  533.         """
    
  534.         Regression test for ticket #17946.
    
  535.         """
    
  536.         management.call_command(
    
  537.             "loaddata",
    
  538.             "m2mtoself.json",
    
  539.             verbosity=0,
    
  540.         )
    
  541. 
    
  542.     @override_settings(
    
  543.         FIXTURE_DIRS=[
    
  544.             os.path.join(_cur_dir, "fixtures_1"),
    
  545.             os.path.join(_cur_dir, "fixtures_1"),
    
  546.         ]
    
  547.     )
    
  548.     def test_fixture_dirs_with_duplicates(self):
    
  549.         """
    
  550.         settings.FIXTURE_DIRS cannot contain duplicates in order to avoid
    
  551.         repeated fixture loading.
    
  552.         """
    
  553.         with self.assertRaisesMessage(
    
  554.             ImproperlyConfigured, "settings.FIXTURE_DIRS contains duplicates."
    
  555.         ):
    
  556.             management.call_command("loaddata", "absolute.json", verbosity=0)
    
  557. 
    
  558.     @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, "fixtures")])
    
  559.     def test_fixture_dirs_with_default_fixture_path(self):
    
  560.         """
    
  561.         settings.FIXTURE_DIRS cannot contain a default fixtures directory
    
  562.         for application (app/fixtures) in order to avoid repeated fixture loading.
    
  563.         """
    
  564.         msg = (
    
  565.             "'%s' is a default fixture directory for the '%s' app "
    
  566.             "and cannot be listed in settings.FIXTURE_DIRS."
    
  567.             % (os.path.join(_cur_dir, "fixtures"), "fixtures_regress")
    
  568.         )
    
  569.         with self.assertRaisesMessage(ImproperlyConfigured, msg):
    
  570.             management.call_command("loaddata", "absolute.json", verbosity=0)
    
  571. 
    
  572.     @override_settings(
    
  573.         FIXTURE_DIRS=[
    
  574.             os.path.join(_cur_dir, "fixtures_1"),
    
  575.             os.path.join(_cur_dir, "fixtures_2"),
    
  576.         ]
    
  577.     )
    
  578.     def test_loaddata_with_valid_fixture_dirs(self):
    
  579.         management.call_command(
    
  580.             "loaddata",
    
  581.             "absolute.json",
    
  582.             verbosity=0,
    
  583.         )
    
  584. 
    
  585.     @override_settings(FIXTURE_DIRS=[Path(_cur_dir) / "fixtures_1"])
    
  586.     def test_fixtures_dir_pathlib(self):
    
  587.         management.call_command("loaddata", "inner/absolute.json", verbosity=0)
    
  588.         self.assertQuerysetEqual(Absolute.objects.all(), [1], transform=lambda o: o.pk)
    
  589. 
    
  590. 
    
  591. class NaturalKeyFixtureTests(TestCase):
    
  592.     def test_nk_deserialize(self):
    
  593.         """
    
  594.         Test for ticket #13030 - Python based parser version
    
  595.         natural keys deserialize with fk to inheriting model
    
  596.         """
    
  597.         management.call_command(
    
  598.             "loaddata",
    
  599.             "model-inheritance.json",
    
  600.             verbosity=0,
    
  601.         )
    
  602.         management.call_command(
    
  603.             "loaddata",
    
  604.             "nk-inheritance.json",
    
  605.             verbosity=0,
    
  606.         )
    
  607.         self.assertEqual(NKChild.objects.get(pk=1).data, "apple")
    
  608. 
    
  609.         self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, "apple")
    
  610. 
    
  611.     def test_nk_deserialize_xml(self):
    
  612.         """
    
  613.         Test for ticket #13030 - XML version
    
  614.         natural keys deserialize with fk to inheriting model
    
  615.         """
    
  616.         management.call_command(
    
  617.             "loaddata",
    
  618.             "model-inheritance.json",
    
  619.             verbosity=0,
    
  620.         )
    
  621.         management.call_command(
    
  622.             "loaddata",
    
  623.             "nk-inheritance.json",
    
  624.             verbosity=0,
    
  625.         )
    
  626.         management.call_command(
    
  627.             "loaddata",
    
  628.             "nk-inheritance2.xml",
    
  629.             verbosity=0,
    
  630.         )
    
  631.         self.assertEqual(NKChild.objects.get(pk=2).data, "banana")
    
  632.         self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, "apple")
    
  633. 
    
  634.     def test_nk_on_serialize(self):
    
  635.         """
    
  636.         Natural key requirements are taken into account when serializing models.
    
  637.         """
    
  638.         management.call_command(
    
  639.             "loaddata",
    
  640.             "forward_ref_lookup.json",
    
  641.             verbosity=0,
    
  642.         )
    
  643. 
    
  644.         out = StringIO()
    
  645.         management.call_command(
    
  646.             "dumpdata",
    
  647.             "fixtures_regress.book",
    
  648.             "fixtures_regress.person",
    
  649.             "fixtures_regress.store",
    
  650.             verbosity=0,
    
  651.             format="json",
    
  652.             use_natural_foreign_keys=True,
    
  653.             use_natural_primary_keys=True,
    
  654.             stdout=out,
    
  655.         )
    
  656.         self.assertJSONEqual(
    
  657.             out.getvalue(),
    
  658.             """
    
  659.             [{"fields": {"main": null, "name": "Amazon"},
    
  660.             "model": "fixtures_regress.store"},
    
  661.             {"fields": {"main": null, "name": "Borders"},
    
  662.             "model": "fixtures_regress.store"},
    
  663.             {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"},
    
  664.             {"pk": 1, "model": "fixtures_regress.book",
    
  665.             "fields": {"stores": [["Amazon"], ["Borders"]],
    
  666.             "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]
    
  667.             """,
    
  668.         )
    
  669. 
    
  670.     def test_dependency_sorting(self):
    
  671.         """
    
  672.         It doesn't matter what order you mention the models,  Store *must* be
    
  673.         serialized before then Person, and both must be serialized before Book.
    
  674.         """
    
  675.         sorted_deps = serializers.sort_dependencies(
    
  676.             [("fixtures_regress", [Book, Person, Store])]
    
  677.         )
    
  678.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  679. 
    
  680.     def test_dependency_sorting_2(self):
    
  681.         sorted_deps = serializers.sort_dependencies(
    
  682.             [("fixtures_regress", [Book, Store, Person])]
    
  683.         )
    
  684.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  685. 
    
  686.     def test_dependency_sorting_3(self):
    
  687.         sorted_deps = serializers.sort_dependencies(
    
  688.             [("fixtures_regress", [Store, Book, Person])]
    
  689.         )
    
  690.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  691. 
    
  692.     def test_dependency_sorting_4(self):
    
  693.         sorted_deps = serializers.sort_dependencies(
    
  694.             [("fixtures_regress", [Store, Person, Book])]
    
  695.         )
    
  696.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  697. 
    
  698.     def test_dependency_sorting_5(self):
    
  699.         sorted_deps = serializers.sort_dependencies(
    
  700.             [("fixtures_regress", [Person, Book, Store])]
    
  701.         )
    
  702.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  703. 
    
  704.     def test_dependency_sorting_6(self):
    
  705.         sorted_deps = serializers.sort_dependencies(
    
  706.             [("fixtures_regress", [Person, Store, Book])]
    
  707.         )
    
  708.         self.assertEqual(sorted_deps, [Store, Person, Book])
    
  709. 
    
  710.     def test_dependency_sorting_dangling(self):
    
  711.         sorted_deps = serializers.sort_dependencies(
    
  712.             [("fixtures_regress", [Person, Circle1, Store, Book])]
    
  713.         )
    
  714.         self.assertEqual(sorted_deps, [Circle1, Store, Person, Book])
    
  715. 
    
  716.     def test_dependency_sorting_tight_circular(self):
    
  717.         with self.assertRaisesMessage(
    
  718.             RuntimeError,
    
  719.             "Can't resolve dependencies for fixtures_regress.Circle1, "
    
  720.             "fixtures_regress.Circle2 in serialized app list.",
    
  721.         ):
    
  722.             serializers.sort_dependencies(
    
  723.                 [("fixtures_regress", [Person, Circle2, Circle1, Store, Book])]
    
  724.             )
    
  725. 
    
  726.     def test_dependency_sorting_tight_circular_2(self):
    
  727.         with self.assertRaisesMessage(
    
  728.             RuntimeError,
    
  729.             "Can't resolve dependencies for fixtures_regress.Circle1, "
    
  730.             "fixtures_regress.Circle2 in serialized app list.",
    
  731.         ):
    
  732.             serializers.sort_dependencies(
    
  733.                 [("fixtures_regress", [Circle1, Book, Circle2])]
    
  734.             )
    
  735. 
    
  736.     def test_dependency_self_referential(self):
    
  737.         with self.assertRaisesMessage(
    
  738.             RuntimeError,
    
  739.             "Can't resolve dependencies for fixtures_regress.Circle3 in "
    
  740.             "serialized app list.",
    
  741.         ):
    
  742.             serializers.sort_dependencies([("fixtures_regress", [Book, Circle3])])
    
  743. 
    
  744.     def test_dependency_sorting_long(self):
    
  745.         with self.assertRaisesMessage(
    
  746.             RuntimeError,
    
  747.             "Can't resolve dependencies for fixtures_regress.Circle1, "
    
  748.             "fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized "
    
  749.             "app list.",
    
  750.         ):
    
  751.             serializers.sort_dependencies(
    
  752.                 [("fixtures_regress", [Person, Circle2, Circle1, Circle3, Store, Book])]
    
  753.             )
    
  754. 
    
  755.     def test_dependency_sorting_normal(self):
    
  756.         sorted_deps = serializers.sort_dependencies(
    
  757.             [("fixtures_regress", [Person, ExternalDependency, Book])]
    
  758.         )
    
  759.         self.assertEqual(sorted_deps, [Person, Book, ExternalDependency])
    
  760. 
    
  761.     def test_normal_pk(self):
    
  762.         """
    
  763.         Normal primary keys work on a model with natural key capabilities.
    
  764.         """
    
  765.         management.call_command(
    
  766.             "loaddata",
    
  767.             "non_natural_1.json",
    
  768.             verbosity=0,
    
  769.         )
    
  770.         management.call_command(
    
  771.             "loaddata",
    
  772.             "forward_ref_lookup.json",
    
  773.             verbosity=0,
    
  774.         )
    
  775.         management.call_command(
    
  776.             "loaddata",
    
  777.             "non_natural_2.xml",
    
  778.             verbosity=0,
    
  779.         )
    
  780.         books = Book.objects.all()
    
  781.         self.assertQuerysetEqual(
    
  782.             books,
    
  783.             [
    
  784.                 "<Book: Cryptonomicon by Neal Stephenson (available at Amazon, "
    
  785.                 "Borders)>",
    
  786.                 "<Book: Ender's Game by Orson Scott Card (available at Collins "
    
  787.                 "Bookstore)>",
    
  788.                 "<Book: Permutation City by Greg Egan (available at Angus and "
    
  789.                 "Robertson)>",
    
  790.             ],
    
  791.             transform=repr,
    
  792.         )
    
  793. 
    
  794. 
    
  795. class NaturalKeyFixtureOnOtherDatabaseTests(TestCase):
    
  796.     databases = {"other"}
    
  797. 
    
  798.     def test_natural_key_dependencies(self):
    
  799.         """
    
  800.         Natural keys with foreing keys in dependencies works in a multiple
    
  801.         database setup.
    
  802.         """
    
  803.         management.call_command(
    
  804.             "loaddata",
    
  805.             "nk_with_foreign_key.json",
    
  806.             database="other",
    
  807.             verbosity=0,
    
  808.         )
    
  809.         obj = NaturalKeyWithFKDependency.objects.using("other").get()
    
  810.         self.assertEqual(obj.name, "The Lord of the Rings")
    
  811.         self.assertEqual(obj.author.name, "J.R.R. Tolkien")
    
  812. 
    
  813. 
    
  814. class M2MNaturalKeyFixtureTests(TestCase):
    
  815.     """Tests for ticket #14426."""
    
  816. 
    
  817.     def test_dependency_sorting_m2m_simple(self):
    
  818.         """
    
  819.         M2M relations without explicit through models SHOULD count as dependencies
    
  820. 
    
  821.         Regression test for bugs that could be caused by flawed fixes to
    
  822.         #14226, namely if M2M checks are removed from sort_dependencies
    
  823.         altogether.
    
  824.         """
    
  825.         sorted_deps = serializers.sort_dependencies(
    
  826.             [("fixtures_regress", [M2MSimpleA, M2MSimpleB])]
    
  827.         )
    
  828.         self.assertEqual(sorted_deps, [M2MSimpleB, M2MSimpleA])
    
  829. 
    
  830.     def test_dependency_sorting_m2m_simple_circular(self):
    
  831.         """
    
  832.         Resolving circular M2M relations without explicit through models should
    
  833.         fail loudly
    
  834.         """
    
  835.         with self.assertRaisesMessage(
    
  836.             RuntimeError,
    
  837.             "Can't resolve dependencies for fixtures_regress.M2MSimpleCircularA, "
    
  838.             "fixtures_regress.M2MSimpleCircularB in serialized app list.",
    
  839.         ):
    
  840.             serializers.sort_dependencies(
    
  841.                 [("fixtures_regress", [M2MSimpleCircularA, M2MSimpleCircularB])]
    
  842.             )
    
  843. 
    
  844.     def test_dependency_sorting_m2m_complex(self):
    
  845.         """
    
  846.         M2M relations with explicit through models should NOT count as
    
  847.         dependencies.  The through model itself will have dependencies, though.
    
  848.         """
    
  849.         sorted_deps = serializers.sort_dependencies(
    
  850.             [("fixtures_regress", [M2MComplexA, M2MComplexB, M2MThroughAB])]
    
  851.         )
    
  852.         # Order between M2MComplexA and M2MComplexB doesn't matter. The through
    
  853.         # model has dependencies to them though, so it should come last.
    
  854.         self.assertEqual(sorted_deps[-1], M2MThroughAB)
    
  855. 
    
  856.     def test_dependency_sorting_m2m_complex_circular_1(self):
    
  857.         """
    
  858.         Circular M2M relations with explicit through models should be serializable
    
  859.         """
    
  860.         A, B, C, AtoB, BtoC, CtoA = (
    
  861.             M2MComplexCircular1A,
    
  862.             M2MComplexCircular1B,
    
  863.             M2MComplexCircular1C,
    
  864.             M2MCircular1ThroughAB,
    
  865.             M2MCircular1ThroughBC,
    
  866.             M2MCircular1ThroughCA,
    
  867.         )
    
  868.         sorted_deps = serializers.sort_dependencies(
    
  869.             [("fixtures_regress", [A, B, C, AtoB, BtoC, CtoA])]
    
  870.         )
    
  871.         # The dependency sorting should not result in an error, and the
    
  872.         # through model should have dependencies to the other models and as
    
  873.         # such come last in the list.
    
  874.         self.assertEqual(sorted_deps[:3], [A, B, C])
    
  875.         self.assertEqual(sorted_deps[3:], [AtoB, BtoC, CtoA])
    
  876. 
    
  877.     def test_dependency_sorting_m2m_complex_circular_2(self):
    
  878.         """
    
  879.         Circular M2M relations with explicit through models should be serializable
    
  880.         This test tests the circularity with explicit natural_key.dependencies
    
  881.         """
    
  882.         sorted_deps = serializers.sort_dependencies(
    
  883.             [
    
  884.                 (
    
  885.                     "fixtures_regress",
    
  886.                     [M2MComplexCircular2A, M2MComplexCircular2B, M2MCircular2ThroughAB],
    
  887.                 )
    
  888.             ]
    
  889.         )
    
  890.         self.assertEqual(sorted_deps[:2], [M2MComplexCircular2A, M2MComplexCircular2B])
    
  891.         self.assertEqual(sorted_deps[2:], [M2MCircular2ThroughAB])
    
  892. 
    
  893.     def test_dump_and_load_m2m_simple(self):
    
  894.         """
    
  895.         Test serializing and deserializing back models with simple M2M relations
    
  896.         """
    
  897.         a = M2MSimpleA.objects.create(data="a")
    
  898.         b1 = M2MSimpleB.objects.create(data="b1")
    
  899.         b2 = M2MSimpleB.objects.create(data="b2")
    
  900.         a.b_set.add(b1)
    
  901.         a.b_set.add(b2)
    
  902. 
    
  903.         out = StringIO()
    
  904.         management.call_command(
    
  905.             "dumpdata",
    
  906.             "fixtures_regress.M2MSimpleA",
    
  907.             "fixtures_regress.M2MSimpleB",
    
  908.             use_natural_foreign_keys=True,
    
  909.             stdout=out,
    
  910.         )
    
  911. 
    
  912.         for model in [M2MSimpleA, M2MSimpleB]:
    
  913.             model.objects.all().delete()
    
  914. 
    
  915.         objects = serializers.deserialize("json", out.getvalue())
    
  916.         for obj in objects:
    
  917.             obj.save()
    
  918. 
    
  919.         new_a = M2MSimpleA.objects.get_by_natural_key("a")
    
  920.         self.assertCountEqual(new_a.b_set.all(), [b1, b2])
    
  921. 
    
  922. 
    
  923. class TestTicket11101(TransactionTestCase):
    
  924.     available_apps = ["fixtures_regress"]
    
  925. 
    
  926.     @skipUnlessDBFeature("supports_transactions")
    
  927.     def test_ticket_11101(self):
    
  928.         """Fixtures can be rolled back (ticket #11101)."""
    
  929.         with transaction.atomic():
    
  930.             management.call_command(
    
  931.                 "loaddata",
    
  932.                 "thingy.json",
    
  933.                 verbosity=0,
    
  934.             )
    
  935.             self.assertEqual(Thingy.objects.count(), 1)
    
  936.             transaction.set_rollback(True)
    
  937.         self.assertEqual(Thingy.objects.count(), 0)
    
  938. 
    
  939. 
    
  940. class TestLoadFixtureFromOtherAppDirectory(TestCase):
    
  941.     """
    
  942.     #23612 -- fixtures path should be normalized to allow referencing relative
    
  943.     paths on Windows.
    
  944.     """
    
  945. 
    
  946.     current_dir = os.path.abspath(os.path.dirname(__file__))
    
  947.     # relative_prefix is something like tests/fixtures_regress or
    
  948.     # fixtures_regress depending on how runtests.py is invoked.
    
  949.     # All path separators must be / in order to be a proper regression test on
    
  950.     # Windows, so replace as appropriate.
    
  951.     relative_prefix = os.path.relpath(current_dir, os.getcwd()).replace("\\", "/")
    
  952.     fixtures = [relative_prefix + "/fixtures/absolute.json"]
    
  953. 
    
  954.     def test_fixtures_loaded(self):
    
  955.         count = Absolute.objects.count()
    
  956.         self.assertGreater(count, 0, "Fixtures not loaded properly.")