tests.py 32 KB

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