tests.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  1. import os
  2. import sys
  3. import tempfile
  4. import unittest
  5. import warnings
  6. from io import StringIO
  7. from unittest import mock
  8. from django.apps import apps
  9. from django.contrib.sites.models import Site
  10. from django.core import management
  11. from django.core.files.temp import NamedTemporaryFile
  12. from django.core.management import CommandError
  13. from django.core.management.commands.dumpdata import ProxyModelWarning
  14. from django.core.serializers.base import ProgressBar
  15. from django.db import IntegrityError, connection
  16. from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
  17. from .models import (
  18. Article, Category, CircularA, CircularB, NaturalKeyThing,
  19. PrimaryKeyUUIDModel, ProxySpy, Spy, Tag, Visa,
  20. )
  21. try:
  22. import bz2 # NOQA
  23. HAS_BZ2 = True
  24. except ImportError:
  25. HAS_BZ2 = False
  26. try:
  27. import lzma # NOQA
  28. HAS_LZMA = True
  29. except ImportError:
  30. HAS_LZMA = False
  31. class TestCaseFixtureLoadingTests(TestCase):
  32. fixtures = ['fixture1.json', 'fixture2.json']
  33. def test_class_fixtures(self):
  34. "Test case has installed 3 fixture objects"
  35. self.assertSequenceEqual(
  36. Article.objects.values_list('headline', flat=True), [
  37. 'Django conquers world!',
  38. 'Copyright is fine the way it is',
  39. 'Poker has no place on ESPN',
  40. ],
  41. )
  42. class SubclassTestCaseFixtureLoadingTests(TestCaseFixtureLoadingTests):
  43. """
  44. Make sure that subclasses can remove fixtures from parent class (#21089).
  45. """
  46. fixtures = []
  47. def test_class_fixtures(self):
  48. "There were no fixture objects installed"
  49. self.assertEqual(Article.objects.count(), 0)
  50. class DumpDataAssertMixin:
  51. def _dumpdata_assert(self, args, output, format='json', filename=None,
  52. natural_foreign_keys=False, natural_primary_keys=False,
  53. use_base_manager=False, exclude_list=[], primary_keys=''):
  54. new_io = StringIO()
  55. filename = filename and os.path.join(tempfile.gettempdir(), filename)
  56. management.call_command(
  57. 'dumpdata',
  58. *args,
  59. format=format,
  60. stdout=new_io,
  61. stderr=new_io,
  62. output=filename,
  63. use_natural_foreign_keys=natural_foreign_keys,
  64. use_natural_primary_keys=natural_primary_keys,
  65. use_base_manager=use_base_manager,
  66. exclude=exclude_list,
  67. primary_keys=primary_keys,
  68. )
  69. if filename:
  70. with open(filename) as f:
  71. command_output = f.read()
  72. os.remove(filename)
  73. else:
  74. command_output = new_io.getvalue().strip()
  75. if format == "json":
  76. self.assertJSONEqual(command_output, output)
  77. elif format == "xml":
  78. self.assertXMLEqual(command_output, output)
  79. else:
  80. self.assertEqual(command_output, output)
  81. class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
  82. def test_loading_and_dumping(self):
  83. apps.clear_cache()
  84. Site.objects.all().delete()
  85. # Load fixture 1. Single JSON file, with two objects.
  86. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  87. self.assertSequenceEqual(
  88. Article.objects.values_list('headline', flat=True),
  89. ['Time to reform copyright', 'Poker has no place on ESPN'],
  90. )
  91. # Dump the current contents of the database as a JSON fixture
  92. self._dumpdata_assert(
  93. ['fixtures'],
  94. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  95. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  96. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  97. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  98. )
  99. # Try just dumping the contents of fixtures.Category
  100. self._dumpdata_assert(
  101. ['fixtures.Category'],
  102. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", '
  103. '"title": "News Stories"}}]'
  104. )
  105. # ...and just fixtures.Article
  106. self._dumpdata_assert(
  107. ['fixtures.Article'],
  108. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  109. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
  110. '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  111. )
  112. # ...and both
  113. self._dumpdata_assert(
  114. ['fixtures.Category', 'fixtures.Article'],
  115. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", '
  116. '"title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has '
  117. 'no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", '
  118. '"fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  119. )
  120. # Specify a specific model twice
  121. self._dumpdata_assert(
  122. ['fixtures.Article', 'fixtures.Article'],
  123. (
  124. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  125. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
  126. '"Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  127. )
  128. )
  129. # Specify a dump that specifies Article both explicitly and implicitly
  130. self._dumpdata_assert(
  131. ['fixtures.Article', 'fixtures'],
  132. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  133. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  134. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  135. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  136. )
  137. # Specify a dump that specifies Article both explicitly and implicitly,
  138. # but lists the app first (#22025).
  139. self._dumpdata_assert(
  140. ['fixtures', 'fixtures.Article'],
  141. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  142. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  143. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  144. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  145. )
  146. # Same again, but specify in the reverse order
  147. self._dumpdata_assert(
  148. ['fixtures'],
  149. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  150. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no '
  151. 'place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields":'
  152. ' {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  153. )
  154. # Specify one model from one application, and an entire other application.
  155. self._dumpdata_assert(
  156. ['fixtures.Category', 'sites'],
  157. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  158. '"News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": '
  159. '"example.com"}}]'
  160. )
  161. # Load fixture 2. JSON file imported by default. Overwrites some existing objects
  162. management.call_command('loaddata', 'fixture2.json', verbosity=0)
  163. self.assertSequenceEqual(
  164. Article.objects.values_list('headline', flat=True),
  165. [
  166. 'Django conquers world!',
  167. 'Copyright is fine the way it is',
  168. 'Poker has no place on ESPN',
  169. ],
  170. )
  171. # Load fixture 3, XML format.
  172. management.call_command('loaddata', 'fixture3.xml', verbosity=0)
  173. self.assertSequenceEqual(
  174. Article.objects.values_list('headline', flat=True),
  175. [
  176. 'XML identified as leading cause of cancer',
  177. 'Django conquers world!',
  178. 'Copyright is fine the way it is',
  179. 'Poker on TV is great!',
  180. ],
  181. )
  182. # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne.
  183. management.call_command('loaddata', 'fixture6.json', verbosity=0)
  184. self.assertQuerysetEqual(Tag.objects.all(), [
  185. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  186. '<Tag: <Article: Copyright is fine the way it is> tagged "law">',
  187. ], transform=repr, ordered=False)
  188. # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne.
  189. management.call_command('loaddata', 'fixture7.xml', verbosity=0)
  190. self.assertQuerysetEqual(Tag.objects.all(), [
  191. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  192. '<Tag: <Article: Copyright is fine the way it is> tagged "legal">',
  193. '<Tag: <Article: Django conquers world!> tagged "django">',
  194. '<Tag: <Article: Django conquers world!> tagged "world domination">',
  195. ], transform=repr, ordered=False)
  196. # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany.
  197. management.call_command('loaddata', 'fixture8.json', verbosity=0)
  198. self.assertQuerysetEqual(Visa.objects.all(), [
  199. '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
  200. '<Visa: Stephane Grappelli Can add user>',
  201. '<Visa: Prince >'
  202. ], transform=repr, ordered=False)
  203. # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany.
  204. management.call_command('loaddata', 'fixture9.xml', verbosity=0)
  205. self.assertQuerysetEqual(Visa.objects.all(), [
  206. '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
  207. '<Visa: Stephane Grappelli Can add user, Can delete user>',
  208. '<Visa: Artist formerly known as "Prince" Can change user>'
  209. ], transform=repr, ordered=False)
  210. # object list is unaffected
  211. self.assertSequenceEqual(
  212. Article.objects.values_list('headline', flat=True),
  213. [
  214. 'XML identified as leading cause of cancer',
  215. 'Django conquers world!',
  216. 'Copyright is fine the way it is',
  217. 'Poker on TV is great!',
  218. ],
  219. )
  220. # By default, you get raw keys on dumpdata
  221. self._dumpdata_assert(
  222. ['fixtures.book'],
  223. '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]'
  224. )
  225. # But you can get natural keys if you ask for them and they are available
  226. self._dumpdata_assert(
  227. ['fixtures.book'],
  228. '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
  229. 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
  230. natural_foreign_keys=True
  231. )
  232. # You can also omit the primary keys for models that we can get later with natural keys.
  233. self._dumpdata_assert(
  234. ['fixtures.person'],
  235. '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane '
  236. 'Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as '
  237. '\\"Prince\\""}, "model": "fixtures.person"}]',
  238. natural_primary_keys=True
  239. )
  240. # Dump the current contents of the database as a JSON fixture
  241. self._dumpdata_assert(
  242. ['fixtures'],
  243. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  244. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is '
  245. 'great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  246. '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, '
  247. '"model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": '
  248. '"2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML '
  249. 'identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": '
  250. '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
  251. '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
  252. '"legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", '
  253. '"article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": '
  254. '{"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, '
  255. '"model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": '
  256. '"fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", '
  257. '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", '
  258. '"fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], '
  259. '["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": '
  260. '"fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", '
  261. '"user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person":'
  262. ' ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, '
  263. '{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist '
  264. 'formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
  265. natural_foreign_keys=True
  266. )
  267. # Dump the current contents of the database as an XML fixture
  268. self._dumpdata_assert(
  269. ['fixtures'],
  270. '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
  271. 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
  272. 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
  273. 'model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field '
  274. 'type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field></object><object pk="3" '
  275. 'model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it '
  276. 'is</field><field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field></object><object '
  277. 'pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!'
  278. '</field><field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field></object><object '
  279. 'pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading '
  280. 'cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
  281. '</object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field>'
  282. '<field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures'
  283. '</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3'
  284. '</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal'
  285. '</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>'
  286. 'fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" '
  287. 'name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" '
  288. 'name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" '
  289. 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field '
  290. 'type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag">'
  291. '<field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" '
  292. 'name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field>'
  293. '<field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="1" '
  294. 'model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object>'
  295. '<object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli'
  296. '</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
  297. 'Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.visa"><field '
  298. 'to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field>'
  299. '<field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user'
  300. '</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user'
  301. '</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user'
  302. '</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" '
  303. 'model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane'
  304. ' Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel">'
  305. '<object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object>'
  306. '<natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field>'
  307. '</object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" '
  308. 'rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field '
  309. 'to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural>'
  310. '<natural>auth</natural><natural>user</natural></object></field></object><object pk="1" '
  311. 'model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field '
  312. 'to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as '
  313. '"Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object>'
  314. '</django-objects>',
  315. format='xml', natural_foreign_keys=True
  316. )
  317. def test_dumpdata_with_excludes(self):
  318. # Load fixture1 which has a site, two articles, and a category
  319. Site.objects.all().delete()
  320. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  321. # Excluding fixtures app should only leave sites
  322. self._dumpdata_assert(
  323. ['sites', 'fixtures'],
  324. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
  325. exclude_list=['fixtures'],
  326. )
  327. # Excluding fixtures.Article/Book should leave fixtures.Category
  328. self._dumpdata_assert(
  329. ['sites', 'fixtures'],
  330. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
  331. '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  332. '"News Stories"}}]',
  333. exclude_list=['fixtures.Article', 'fixtures.Book']
  334. )
  335. # Excluding fixtures and fixtures.Article/Book should be a no-op
  336. self._dumpdata_assert(
  337. ['sites', 'fixtures'],
  338. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, '
  339. '{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  340. '"News Stories"}}]',
  341. exclude_list=['fixtures.Article', 'fixtures.Book']
  342. )
  343. # Excluding sites and fixtures.Article/Book should only leave fixtures.Category
  344. self._dumpdata_assert(
  345. ['sites', 'fixtures'],
  346. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  347. '"News Stories"}}]',
  348. exclude_list=['fixtures.Article', 'fixtures.Book', 'sites']
  349. )
  350. # Excluding a bogus app should throw an error
  351. with self.assertRaisesMessage(management.CommandError, "No installed app with label 'foo_app'."):
  352. self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app'])
  353. # Excluding a bogus model should throw an error
  354. with self.assertRaisesMessage(management.CommandError, "Unknown model: fixtures.FooModel"):
  355. self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel'])
  356. @unittest.skipIf(sys.platform == 'win32', "Windows doesn't support '?' in filenames.")
  357. def test_load_fixture_with_special_characters(self):
  358. management.call_command('loaddata', 'fixture_with[special]chars', verbosity=0)
  359. self.assertEqual(
  360. Article.objects.get().headline,
  361. 'How To Deal With Special Characters',
  362. )
  363. def test_dumpdata_with_filtering_manager(self):
  364. spy1 = Spy.objects.create(name='Paul')
  365. spy2 = Spy.objects.create(name='Alex', cover_blown=True)
  366. self.assertSequenceEqual(Spy.objects.all(), [spy1])
  367. # Use the default manager
  368. self._dumpdata_assert(
  369. ['fixtures.Spy'],
  370. '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk
  371. )
  372. # Dump using Django's base manager. Should return all objects,
  373. # even those normally filtered by the manager
  374. self._dumpdata_assert(
  375. ['fixtures.Spy'],
  376. '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": '
  377. '"fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk),
  378. use_base_manager=True
  379. )
  380. def test_dumpdata_with_pks(self):
  381. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  382. management.call_command('loaddata', 'fixture2.json', verbosity=0)
  383. self._dumpdata_assert(
  384. ['fixtures.Article'],
  385. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  386. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": '
  387. '"Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  388. primary_keys='2,3'
  389. )
  390. self._dumpdata_assert(
  391. ['fixtures.Article'],
  392. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  393. '"pub_date": "2006-06-16T12:00:00"}}]',
  394. primary_keys='2'
  395. )
  396. with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
  397. self._dumpdata_assert(
  398. ['fixtures'],
  399. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  400. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  401. '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  402. primary_keys='2,3'
  403. )
  404. with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
  405. self._dumpdata_assert(
  406. '',
  407. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  408. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  409. '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  410. primary_keys='2,3'
  411. )
  412. with self.assertRaisesMessage(management.CommandError, "You can only use --pks option with one model"):
  413. self._dumpdata_assert(
  414. ['fixtures.Article', 'fixtures.category'],
  415. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", '
  416. '"pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  417. '{"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  418. primary_keys='2,3'
  419. )
  420. def test_dumpdata_with_uuid_pks(self):
  421. m1 = PrimaryKeyUUIDModel.objects.create()
  422. m2 = PrimaryKeyUUIDModel.objects.create()
  423. output = StringIO()
  424. management.call_command(
  425. 'dumpdata', 'fixtures.PrimaryKeyUUIDModel', '--pks', ', '.join([str(m1.id), str(m2.id)]),
  426. stdout=output,
  427. )
  428. result = output.getvalue()
  429. self.assertIn('"pk": "%s"' % m1.id, result)
  430. self.assertIn('"pk": "%s"' % m2.id, result)
  431. def test_dumpdata_with_file_output(self):
  432. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  433. self._dumpdata_assert(
  434. ['fixtures'],
  435. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  436. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  437. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  438. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
  439. filename='dumpdata.json'
  440. )
  441. def test_dumpdata_progressbar(self):
  442. """
  443. Dumpdata shows a progress bar on the command line when --output is set,
  444. stdout is a tty, and verbosity > 0.
  445. """
  446. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  447. new_io = StringIO()
  448. new_io.isatty = lambda: True
  449. with NamedTemporaryFile() as file:
  450. options = {
  451. 'format': 'json',
  452. 'stdout': new_io,
  453. 'stderr': new_io,
  454. 'output': file.name,
  455. }
  456. management.call_command('dumpdata', 'fixtures', **options)
  457. self.assertTrue(new_io.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n'))
  458. # Test no progress bar when verbosity = 0
  459. options['verbosity'] = 0
  460. new_io = StringIO()
  461. new_io.isatty = lambda: True
  462. options.update({'stdout': new_io, 'stderr': new_io})
  463. management.call_command('dumpdata', 'fixtures', **options)
  464. self.assertEqual(new_io.getvalue(), '')
  465. def test_dumpdata_proxy_without_concrete(self):
  466. """
  467. A warning is displayed if a proxy model is dumped without its concrete
  468. parent.
  469. """
  470. ProxySpy.objects.create(name='Paul')
  471. msg = "fixtures.ProxySpy is a proxy model and won't be serialized."
  472. with self.assertWarnsMessage(ProxyModelWarning, msg):
  473. self._dumpdata_assert(['fixtures.ProxySpy'], '[]')
  474. def test_dumpdata_proxy_with_concrete(self):
  475. """
  476. A warning isn't displayed if a proxy model is dumped with its concrete
  477. parent.
  478. """
  479. spy = ProxySpy.objects.create(name='Paul')
  480. with warnings.catch_warnings(record=True) as warning_list:
  481. warnings.simplefilter('always')
  482. self._dumpdata_assert(
  483. ['fixtures.ProxySpy', 'fixtures.Spy'],
  484. '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy.pk
  485. )
  486. self.assertEqual(len(warning_list), 0)
  487. def test_compress_format_loading(self):
  488. # Load fixture 4 (compressed), using format specification
  489. management.call_command('loaddata', 'fixture4.json', verbosity=0)
  490. self.assertEqual(Article.objects.get().headline, 'Django pets kitten')
  491. def test_compressed_specified_loading(self):
  492. # Load fixture 5 (compressed), using format *and* compression specification
  493. management.call_command('loaddata', 'fixture5.json.zip', verbosity=0)
  494. self.assertEqual(
  495. Article.objects.get().headline,
  496. 'WoW subscribers now outnumber readers',
  497. )
  498. def test_compressed_loading(self):
  499. # Load fixture 5 (compressed), only compression specification
  500. management.call_command('loaddata', 'fixture5.zip', verbosity=0)
  501. self.assertEqual(
  502. Article.objects.get().headline,
  503. 'WoW subscribers now outnumber readers',
  504. )
  505. def test_compressed_loading_gzip(self):
  506. management.call_command('loaddata', 'fixture5.json.gz', verbosity=0)
  507. self.assertEqual(
  508. Article.objects.get().headline,
  509. 'WoW subscribers now outnumber readers',
  510. )
  511. @unittest.skipUnless(HAS_BZ2, 'No bz2 library detected.')
  512. def test_compressed_loading_bz2(self):
  513. management.call_command('loaddata', 'fixture5.json.bz2', verbosity=0)
  514. self.assertEqual(
  515. Article.objects.get().headline,
  516. 'WoW subscribers now outnumber readers',
  517. )
  518. @unittest.skipUnless(HAS_LZMA, 'No lzma library detected.')
  519. def test_compressed_loading_lzma(self):
  520. management.call_command('loaddata', 'fixture5.json.lzma', verbosity=0)
  521. self.assertEqual(
  522. Article.objects.get().headline,
  523. 'WoW subscribers now outnumber readers',
  524. )
  525. @unittest.skipUnless(HAS_LZMA, 'No lzma library detected.')
  526. def test_compressed_loading_xz(self):
  527. management.call_command('loaddata', 'fixture5.json.xz', verbosity=0)
  528. self.assertEqual(
  529. Article.objects.get().headline,
  530. 'WoW subscribers now outnumber readers',
  531. )
  532. def test_ambiguous_compressed_fixture(self):
  533. # The name "fixture5" is ambiguous, so loading raises an error.
  534. msg = "Multiple fixtures named 'fixture5'"
  535. with self.assertRaisesMessage(management.CommandError, msg):
  536. management.call_command('loaddata', 'fixture5', verbosity=0)
  537. def test_db_loading(self):
  538. # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
  539. management.call_command('loaddata', 'db_fixture_1', verbosity=0)
  540. management.call_command('loaddata', 'db_fixture_2', verbosity=0)
  541. self.assertSequenceEqual(
  542. Article.objects.values_list('headline', flat=True),
  543. [
  544. 'Who needs more than one database?',
  545. 'Who needs to use compressed data?',
  546. ],
  547. )
  548. def test_loaddata_error_message(self):
  549. """
  550. Loading a fixture which contains an invalid object outputs an error
  551. message which contains the pk of the object that triggered the error.
  552. """
  553. # MySQL needs a little prodding to reject invalid data.
  554. # This won't affect other tests because the database connection
  555. # is closed at the end of each test.
  556. if connection.vendor == 'mysql':
  557. with connection.cursor() as cursor:
  558. cursor.execute("SET sql_mode = 'TRADITIONAL'")
  559. msg = 'Could not load fixtures.Article(pk=1):'
  560. with self.assertRaisesMessage(IntegrityError, msg):
  561. management.call_command('loaddata', 'invalid.json', verbosity=0)
  562. @unittest.skipUnless(connection.vendor == 'postgresql', 'psycopg2 prohibits null characters in data.')
  563. def test_loaddata_null_characters_on_postgresql(self):
  564. msg = (
  565. 'Could not load fixtures.Article(pk=2): '
  566. 'A string literal cannot contain NUL (0x00) characters.'
  567. )
  568. with self.assertRaisesMessage(ValueError, msg):
  569. management.call_command('loaddata', 'null_character_in_field_value.json')
  570. def test_loaddata_app_option(self):
  571. with self.assertRaisesMessage(CommandError, "No fixture named 'db_fixture_1' found."):
  572. management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
  573. self.assertQuerysetEqual(Article.objects.all(), [])
  574. management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="fixtures")
  575. self.assertEqual(
  576. Article.objects.get().headline,
  577. 'Who needs more than one database?',
  578. )
  579. def test_loaddata_verbosity_three(self):
  580. output = StringIO()
  581. management.call_command('loaddata', 'fixture1.json', verbosity=3, stdout=output, stderr=output)
  582. command_output = output.getvalue()
  583. self.assertIn(
  584. "\rProcessed 1 object(s).\rProcessed 2 object(s)."
  585. "\rProcessed 3 object(s).\rProcessed 4 object(s).\n",
  586. command_output
  587. )
  588. def test_loading_using(self):
  589. # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
  590. management.call_command('loaddata', 'db_fixture_1', verbosity=0, database='default')
  591. management.call_command('loaddata', 'db_fixture_2', verbosity=0, database='default')
  592. self.assertSequenceEqual(
  593. Article.objects.values_list('headline', flat=True),
  594. [
  595. 'Who needs more than one database?',
  596. 'Who needs to use compressed data?',
  597. ],
  598. )
  599. def test_unmatched_identifier_loading(self):
  600. # Try to load db fixture 3. This won't load because the database identifier doesn't match
  601. with self.assertRaisesMessage(CommandError, "No fixture named 'db_fixture_3' found."):
  602. management.call_command('loaddata', 'db_fixture_3', verbosity=0)
  603. with self.assertRaisesMessage(CommandError, "No fixture named 'db_fixture_3' found."):
  604. management.call_command('loaddata', 'db_fixture_3', verbosity=0, database='default')
  605. self.assertQuerysetEqual(Article.objects.all(), [])
  606. def test_output_formats(self):
  607. # Load back in fixture 1, we need the articles from it
  608. management.call_command('loaddata', 'fixture1', verbosity=0)
  609. # Try to load fixture 6 using format discovery
  610. management.call_command('loaddata', 'fixture6', verbosity=0)
  611. self.assertQuerysetEqual(Tag.objects.all(), [
  612. '<Tag: <Article: Time to reform copyright> tagged "copyright">',
  613. '<Tag: <Article: Time to reform copyright> tagged "law">'
  614. ], transform=repr, ordered=False)
  615. # Dump the current contents of the database as a JSON fixture
  616. self._dumpdata_assert(
  617. ['fixtures'],
  618. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  619. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  620. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  621. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": '
  622. '"fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": '
  623. '3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": '
  624. '"law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django '
  625. 'Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, '
  626. '{"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]',
  627. natural_foreign_keys=True
  628. )
  629. # Dump the current contents of the database as an XML fixture
  630. self._dumpdata_assert(
  631. ['fixtures'],
  632. '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0"><object pk="1" '
  633. 'model="fixtures.category"><field type="CharField" name="title">News Stories</field><field '
  634. 'type="TextField" name="description">Latest news stories</field></object><object pk="2" '
  635. 'model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field>'
  636. '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" '
  637. 'model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field>'
  638. '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" '
  639. 'model="fixtures.tag"><field type="CharField" name="name">copyright</field><field '
  640. 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
  641. '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
  642. '</object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field '
  643. 'to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural>'
  644. '<natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field>'
  645. '</object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt'
  646. '</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane '
  647. 'Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">'
  648. 'Prince</field></object></django-objects>',
  649. format='xml', natural_foreign_keys=True
  650. )
  651. def test_loading_with_exclude_app(self):
  652. Site.objects.all().delete()
  653. management.call_command('loaddata', 'fixture1', exclude=['fixtures'], verbosity=0)
  654. self.assertFalse(Article.objects.exists())
  655. self.assertFalse(Category.objects.exists())
  656. self.assertEqual(Site.objects.get().domain, 'example.com')
  657. def test_loading_with_exclude_model(self):
  658. Site.objects.all().delete()
  659. management.call_command('loaddata', 'fixture1', exclude=['fixtures.Article'], verbosity=0)
  660. self.assertFalse(Article.objects.exists())
  661. self.assertEqual(Category.objects.get().title, 'News Stories')
  662. self.assertEqual(Site.objects.get().domain, 'example.com')
  663. def test_exclude_option_errors(self):
  664. """Excluding a bogus app or model should raise an error."""
  665. msg = "No installed app with label 'foo_app'."
  666. with self.assertRaisesMessage(management.CommandError, msg):
  667. management.call_command('loaddata', 'fixture1', exclude=['foo_app'], verbosity=0)
  668. msg = "Unknown model: fixtures.FooModel"
  669. with self.assertRaisesMessage(management.CommandError, msg):
  670. management.call_command('loaddata', 'fixture1', exclude=['fixtures.FooModel'], verbosity=0)
  671. def test_stdin_without_format(self):
  672. """Reading from stdin raises an error if format isn't specified."""
  673. msg = '--format must be specified when reading from stdin.'
  674. with self.assertRaisesMessage(management.CommandError, msg):
  675. management.call_command('loaddata', '-', verbosity=0)
  676. def test_loading_stdin(self):
  677. """Loading fixtures from stdin with json and xml."""
  678. tests_dir = os.path.dirname(__file__)
  679. fixture_json = os.path.join(tests_dir, 'fixtures', 'fixture1.json')
  680. fixture_xml = os.path.join(tests_dir, 'fixtures', 'fixture3.xml')
  681. with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_json)):
  682. management.call_command('loaddata', '--format=json', '-', verbosity=0)
  683. self.assertSequenceEqual(
  684. Article.objects.values_list('headline', flat=True),
  685. ['Time to reform copyright', 'Poker has no place on ESPN'],
  686. )
  687. with mock.patch('django.core.management.commands.loaddata.sys.stdin', open(fixture_xml)):
  688. management.call_command('loaddata', '--format=xml', '-', verbosity=0)
  689. self.assertSequenceEqual(
  690. Article.objects.values_list('headline', flat=True),
  691. [
  692. 'XML identified as leading cause of cancer',
  693. 'Time to reform copyright',
  694. 'Poker on TV is great!',
  695. ],
  696. )
  697. class NonexistentFixtureTests(TestCase):
  698. """
  699. Custom class to limit fixture dirs.
  700. """
  701. def test_loaddata_not_existent_fixture_file(self):
  702. stdout_output = StringIO()
  703. with self.assertRaisesMessage(CommandError, "No fixture named 'this_fixture_doesnt_exist' found."):
  704. management.call_command('loaddata', 'this_fixture_doesnt_exist', stdout=stdout_output)
  705. @mock.patch('django.db.connection.enable_constraint_checking')
  706. @mock.patch('django.db.connection.disable_constraint_checking')
  707. def test_nonexistent_fixture_no_constraint_checking(
  708. self, disable_constraint_checking, enable_constraint_checking):
  709. """
  710. If no fixtures match the loaddata command, constraints checks on the
  711. database shouldn't be disabled. This is performance critical on MSSQL.
  712. """
  713. with self.assertRaisesMessage(CommandError, "No fixture named 'this_fixture_doesnt_exist' found."):
  714. management.call_command('loaddata', 'this_fixture_doesnt_exist', verbosity=0)
  715. disable_constraint_checking.assert_not_called()
  716. enable_constraint_checking.assert_not_called()
  717. class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
  718. available_apps = [
  719. 'fixtures',
  720. 'django.contrib.sites',
  721. ]
  722. @skipUnlessDBFeature('supports_forward_references')
  723. def test_format_discovery(self):
  724. # Load fixture 1 again, using format discovery
  725. management.call_command('loaddata', 'fixture1', verbosity=0)
  726. self.assertSequenceEqual(
  727. Article.objects.values_list('headline', flat=True),
  728. ['Time to reform copyright', 'Poker has no place on ESPN'],
  729. )
  730. # Try to load fixture 2 using format discovery; this will fail
  731. # because there are two fixture2's in the fixtures directory
  732. msg = "Multiple fixtures named 'fixture2'"
  733. with self.assertRaisesMessage(management.CommandError, msg):
  734. management.call_command('loaddata', 'fixture2', verbosity=0)
  735. # object list is unaffected
  736. self.assertSequenceEqual(
  737. Article.objects.values_list('headline', flat=True),
  738. ['Time to reform copyright', 'Poker has no place on ESPN'],
  739. )
  740. # Dump the current contents of the database as a JSON fixture
  741. self._dumpdata_assert(
  742. ['fixtures'],
  743. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": '
  744. '"News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place '
  745. 'on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": '
  746. '{"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]'
  747. )
  748. # Load fixture 4 (compressed), using format discovery
  749. management.call_command('loaddata', 'fixture4', verbosity=0)
  750. self.assertSequenceEqual(
  751. Article.objects.values_list('headline', flat=True),
  752. [
  753. 'Django pets kitten',
  754. 'Time to reform copyright',
  755. 'Poker has no place on ESPN',
  756. ],
  757. )
  758. class ForwardReferenceTests(DumpDataAssertMixin, TestCase):
  759. def test_forward_reference_fk(self):
  760. management.call_command('loaddata', 'forward_reference_fk.json', verbosity=0)
  761. t1, t2 = NaturalKeyThing.objects.all()
  762. self.assertEqual(t1.other_thing, t2)
  763. self.assertEqual(t2.other_thing, t1)
  764. self._dumpdata_assert(
  765. ['fixtures'],
  766. '[{"model": "fixtures.naturalkeything", "pk": 1, '
  767. '"fields": {"key": "t1", "other_thing": 2, "other_things": []}}, '
  768. '{"model": "fixtures.naturalkeything", "pk": 2, '
  769. '"fields": {"key": "t2", "other_thing": 1, "other_things": []}}]',
  770. )
  771. def test_forward_reference_fk_natural_key(self):
  772. management.call_command(
  773. 'loaddata',
  774. 'forward_reference_fk_natural_key.json',
  775. verbosity=0,
  776. )
  777. t1, t2 = NaturalKeyThing.objects.all()
  778. self.assertEqual(t1.other_thing, t2)
  779. self.assertEqual(t2.other_thing, t1)
  780. self._dumpdata_assert(
  781. ['fixtures'],
  782. '[{"model": "fixtures.naturalkeything", '
  783. '"fields": {"key": "t1", "other_thing": ["t2"], "other_things": []}}, '
  784. '{"model": "fixtures.naturalkeything", '
  785. '"fields": {"key": "t2", "other_thing": ["t1"], "other_things": []}}]',
  786. natural_primary_keys=True,
  787. natural_foreign_keys=True,
  788. )
  789. def test_forward_reference_m2m(self):
  790. management.call_command('loaddata', 'forward_reference_m2m.json', verbosity=0)
  791. self.assertEqual(NaturalKeyThing.objects.count(), 3)
  792. t1 = NaturalKeyThing.objects.get_by_natural_key('t1')
  793. self.assertSequenceEqual(
  794. t1.other_things.order_by('key').values_list('key', flat=True),
  795. ['t2', 't3'],
  796. )
  797. self._dumpdata_assert(
  798. ['fixtures'],
  799. '[{"model": "fixtures.naturalkeything", "pk": 1, '
  800. '"fields": {"key": "t1", "other_thing": null, "other_things": [2, 3]}}, '
  801. '{"model": "fixtures.naturalkeything", "pk": 2, '
  802. '"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
  803. '{"model": "fixtures.naturalkeything", "pk": 3, '
  804. '"fields": {"key": "t3", "other_thing": null, "other_things": []}}]',
  805. )
  806. def test_forward_reference_m2m_natural_key(self):
  807. management.call_command(
  808. 'loaddata',
  809. 'forward_reference_m2m_natural_key.json',
  810. verbosity=0,
  811. )
  812. self.assertEqual(NaturalKeyThing.objects.count(), 3)
  813. t1 = NaturalKeyThing.objects.get_by_natural_key('t1')
  814. self.assertSequenceEqual(
  815. t1.other_things.order_by('key').values_list('key', flat=True),
  816. ['t2', 't3'],
  817. )
  818. self._dumpdata_assert(
  819. ['fixtures'],
  820. '[{"model": "fixtures.naturalkeything", '
  821. '"fields": {"key": "t1", "other_thing": null, "other_things": [["t2"], ["t3"]]}}, '
  822. '{"model": "fixtures.naturalkeything", '
  823. '"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
  824. '{"model": "fixtures.naturalkeything", '
  825. '"fields": {"key": "t3", "other_thing": null, "other_things": []}}]',
  826. natural_primary_keys=True,
  827. natural_foreign_keys=True,
  828. )
  829. class CircularReferenceTests(DumpDataAssertMixin, TestCase):
  830. def test_circular_reference(self):
  831. management.call_command('loaddata', 'circular_reference.json', verbosity=0)
  832. obj_a = CircularA.objects.get()
  833. obj_b = CircularB.objects.get()
  834. self.assertEqual(obj_a.obj, obj_b)
  835. self.assertEqual(obj_b.obj, obj_a)
  836. self._dumpdata_assert(
  837. ['fixtures'],
  838. '[{"model": "fixtures.circulara", "pk": 1, '
  839. '"fields": {"key": "x", "obj": 1}}, '
  840. '{"model": "fixtures.circularb", "pk": 1, '
  841. '"fields": {"key": "y", "obj": 1}}]',
  842. )
  843. def test_circular_reference_natural_key(self):
  844. management.call_command(
  845. 'loaddata',
  846. 'circular_reference_natural_key.json',
  847. verbosity=0,
  848. )
  849. obj_a = CircularA.objects.get()
  850. obj_b = CircularB.objects.get()
  851. self.assertEqual(obj_a.obj, obj_b)
  852. self.assertEqual(obj_b.obj, obj_a)
  853. self._dumpdata_assert(
  854. ['fixtures'],
  855. '[{"model": "fixtures.circulara", '
  856. '"fields": {"key": "x", "obj": ["y"]}}, '
  857. '{"model": "fixtures.circularb", '
  858. '"fields": {"key": "y", "obj": ["x"]}}]',
  859. natural_primary_keys=True,
  860. natural_foreign_keys=True,
  861. )