tests.py 33 KB

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