tests.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. import gzip
  2. import os
  3. import sys
  4. import tempfile
  5. import unittest
  6. import warnings
  7. from io import StringIO
  8. from unittest import mock
  9. from django.apps import apps
  10. from django.contrib.sites.models import Site
  11. from django.core import management
  12. from django.core.files.temp import NamedTemporaryFile
  13. from django.core.management import CommandError
  14. from django.core.management.commands.dumpdata import ProxyModelWarning
  15. from django.core.serializers.base import ProgressBar
  16. from django.db import IntegrityError, connection
  17. from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
  18. from .models import (
  19. Article,
  20. Category,
  21. CircularA,
  22. CircularB,
  23. NaturalKeyThing,
  24. PrimaryKeyUUIDModel,
  25. ProxySpy,
  26. Spy,
  27. Tag,
  28. Visa,
  29. )
  30. try:
  31. import bz2 # NOQA
  32. HAS_BZ2 = True
  33. except ImportError:
  34. HAS_BZ2 = False
  35. try:
  36. import lzma # NOQA
  37. HAS_LZMA = True
  38. except ImportError:
  39. HAS_LZMA = False
  40. class TestCaseFixtureLoadingTests(TestCase):
  41. fixtures = ["fixture1.json", "fixture2.json"]
  42. def test_class_fixtures(self):
  43. "Test case has installed 3 fixture objects"
  44. self.assertSequenceEqual(
  45. Article.objects.values_list("headline", flat=True),
  46. [
  47. "Django conquers world!",
  48. "Copyright is fine the way it is",
  49. "Poker has no place on ESPN",
  50. ],
  51. )
  52. class SubclassTestCaseFixtureLoadingTests(TestCaseFixtureLoadingTests):
  53. """
  54. Make sure that subclasses can remove fixtures from parent class (#21089).
  55. """
  56. fixtures = []
  57. def test_class_fixtures(self):
  58. "There were no fixture objects installed"
  59. self.assertEqual(Article.objects.count(), 0)
  60. class DumpDataAssertMixin:
  61. def _dumpdata_assert(
  62. self,
  63. args,
  64. output,
  65. format="json",
  66. filename=None,
  67. natural_foreign_keys=False,
  68. natural_primary_keys=False,
  69. use_base_manager=False,
  70. exclude_list=[],
  71. primary_keys="",
  72. ):
  73. new_io = StringIO()
  74. filename = filename and os.path.join(tempfile.gettempdir(), filename)
  75. management.call_command(
  76. "dumpdata",
  77. *args,
  78. format=format,
  79. stdout=new_io,
  80. stderr=new_io,
  81. output=filename,
  82. use_natural_foreign_keys=natural_foreign_keys,
  83. use_natural_primary_keys=natural_primary_keys,
  84. use_base_manager=use_base_manager,
  85. exclude=exclude_list,
  86. primary_keys=primary_keys,
  87. )
  88. if filename:
  89. file_root, file_ext = os.path.splitext(filename)
  90. compression_formats = {
  91. ".bz2": (open, file_root),
  92. ".gz": (gzip.open, filename),
  93. ".lzma": (open, file_root),
  94. ".xz": (open, file_root),
  95. ".zip": (open, file_root),
  96. }
  97. if HAS_BZ2:
  98. compression_formats[".bz2"] = (bz2.open, filename)
  99. if HAS_LZMA:
  100. compression_formats[".lzma"] = (lzma.open, filename)
  101. compression_formats[".xz"] = (lzma.open, filename)
  102. try:
  103. open_method, file_path = compression_formats[file_ext]
  104. except KeyError:
  105. open_method, file_path = open, filename
  106. with open_method(file_path, "rt") as f:
  107. command_output = f.read()
  108. os.remove(file_path)
  109. else:
  110. command_output = new_io.getvalue().strip()
  111. if format == "json":
  112. self.assertJSONEqual(command_output, output)
  113. elif format == "xml":
  114. self.assertXMLEqual(command_output, output)
  115. else:
  116. self.assertEqual(command_output, output)
  117. class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
  118. def test_loading_and_dumping(self):
  119. apps.clear_cache()
  120. Site.objects.all().delete()
  121. # Load fixture 1. Single JSON file, with two objects.
  122. management.call_command("loaddata", "fixture1.json", verbosity=0)
  123. self.assertSequenceEqual(
  124. Article.objects.values_list("headline", flat=True),
  125. ["Time to reform copyright", "Poker has no place on ESPN"],
  126. )
  127. # Dump the current contents of the database as a JSON fixture
  128. self._dumpdata_assert(
  129. ["fixtures"],
  130. '[{"pk": 1, "model": "fixtures.category", "fields": '
  131. '{"description": "Latest news stories", "title": "News Stories"}}, '
  132. '{"pk": 2, "model": "fixtures.article", "fields": '
  133. '{"headline": "Poker has no place on ESPN", '
  134. '"pub_date": "2006-06-16T12:00:00"}}, '
  135. '{"pk": 3, "model": "fixtures.article", "fields": '
  136. '{"headline": "Time to reform copyright", '
  137. '"pub_date": "2006-06-16T13:00:00"}}]',
  138. )
  139. # Try just dumping the contents of fixtures.Category
  140. self._dumpdata_assert(
  141. ["fixtures.Category"],
  142. '[{"pk": 1, "model": "fixtures.category", "fields": '
  143. '{"description": "Latest news stories", "title": "News Stories"}}]',
  144. )
  145. # ...and just fixtures.Article
  146. self._dumpdata_assert(
  147. ["fixtures.Article"],
  148. '[{"pk": 2, "model": "fixtures.article", "fields": '
  149. '{"headline": "Poker has no place on ESPN", '
  150. '"pub_date": "2006-06-16T12:00:00"}}, '
  151. '{"pk": 3, "model": "fixtures.article", "fields": '
  152. '{"headline": "Time to reform copyright", '
  153. '"pub_date": "2006-06-16T13:00:00"}}]',
  154. )
  155. # ...and both
  156. self._dumpdata_assert(
  157. ["fixtures.Category", "fixtures.Article"],
  158. '[{"pk": 1, "model": "fixtures.category", "fields": '
  159. '{"description": "Latest news stories", "title": "News Stories"}}, '
  160. '{"pk": 2, "model": "fixtures.article", "fields": '
  161. '{"headline": "Poker has no place on ESPN", '
  162. '"pub_date": "2006-06-16T12:00:00"}}, '
  163. '{"pk": 3, "model": "fixtures.article", "fields": '
  164. '{"headline": "Time to reform copyright", '
  165. '"pub_date": "2006-06-16T13:00:00"}}]',
  166. )
  167. # Specify a specific model twice
  168. self._dumpdata_assert(
  169. ["fixtures.Article", "fixtures.Article"],
  170. (
  171. '[{"pk": 2, "model": "fixtures.article", "fields": '
  172. '{"headline": "Poker has no place on ESPN", '
  173. '"pub_date": "2006-06-16T12:00:00"}}, '
  174. '{"pk": 3, "model": "fixtures.article", "fields": '
  175. '{"headline": "Time to reform copyright", '
  176. '"pub_date": "2006-06-16T13:00:00"}}]'
  177. ),
  178. )
  179. # Specify a dump that specifies Article both explicitly and implicitly
  180. self._dumpdata_assert(
  181. ["fixtures.Article", "fixtures"],
  182. '[{"pk": 1, "model": "fixtures.category", "fields": '
  183. '{"description": "Latest news stories", "title": "News Stories"}}, '
  184. '{"pk": 2, "model": "fixtures.article", "fields": '
  185. '{"headline": "Poker has no place on ESPN", '
  186. '"pub_date": "2006-06-16T12:00:00"}}, '
  187. '{"pk": 3, "model": "fixtures.article", "fields": '
  188. '{"headline": "Time to reform copyright", '
  189. '"pub_date": "2006-06-16T13:00:00"}}]',
  190. )
  191. # Specify a dump that specifies Article both explicitly and implicitly,
  192. # but lists the app first (#22025).
  193. self._dumpdata_assert(
  194. ["fixtures", "fixtures.Article"],
  195. '[{"pk": 1, "model": "fixtures.category", "fields": '
  196. '{"description": "Latest news stories", "title": "News Stories"}}, '
  197. '{"pk": 2, "model": "fixtures.article", "fields": '
  198. '{"headline": "Poker has no place on ESPN", '
  199. '"pub_date": "2006-06-16T12:00:00"}}, '
  200. '{"pk": 3, "model": "fixtures.article", "fields": '
  201. '{"headline": "Time to reform copyright", '
  202. '"pub_date": "2006-06-16T13:00:00"}}]',
  203. )
  204. # Same again, but specify in the reverse order
  205. self._dumpdata_assert(
  206. ["fixtures"],
  207. '[{"pk": 1, "model": "fixtures.category", "fields": '
  208. '{"description": "Latest news stories", "title": "News Stories"}}, '
  209. '{"pk": 2, "model": "fixtures.article", "fields": '
  210. '{"headline": "Poker has no place on ESPN", '
  211. '"pub_date": "2006-06-16T12:00:00"}}, '
  212. '{"pk": 3, "model": "fixtures.article", "fields": '
  213. '{"headline": "Time to reform copyright", '
  214. '"pub_date": "2006-06-16T13:00:00"}}]',
  215. )
  216. # Specify one model from one application, and an entire other application.
  217. self._dumpdata_assert(
  218. ["fixtures.Category", "sites"],
  219. '[{"pk": 1, "model": "fixtures.category", "fields": '
  220. '{"description": "Latest news stories", "title": "News Stories"}}, '
  221. '{"pk": 1, "model": "sites.site", "fields": '
  222. '{"domain": "example.com", "name": "example.com"}}]',
  223. )
  224. # Load fixture 2. JSON file imported by default. Overwrites some
  225. # existing objects.
  226. management.call_command("loaddata", "fixture2.json", verbosity=0)
  227. self.assertSequenceEqual(
  228. Article.objects.values_list("headline", flat=True),
  229. [
  230. "Django conquers world!",
  231. "Copyright is fine the way it is",
  232. "Poker has no place on ESPN",
  233. ],
  234. )
  235. # Load fixture 3, XML format.
  236. management.call_command("loaddata", "fixture3.xml", verbosity=0)
  237. self.assertSequenceEqual(
  238. Article.objects.values_list("headline", flat=True),
  239. [
  240. "XML identified as leading cause of cancer",
  241. "Django conquers world!",
  242. "Copyright is fine the way it is",
  243. "Poker on TV is great!",
  244. ],
  245. )
  246. # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne.
  247. management.call_command("loaddata", "fixture6.json", verbosity=0)
  248. self.assertQuerySetEqual(
  249. Tag.objects.all(),
  250. [
  251. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  252. '<Tag: <Article: Copyright is fine the way it is> tagged "law">',
  253. ],
  254. transform=repr,
  255. ordered=False,
  256. )
  257. # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne.
  258. management.call_command("loaddata", "fixture7.xml", verbosity=0)
  259. self.assertQuerySetEqual(
  260. Tag.objects.all(),
  261. [
  262. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  263. '<Tag: <Article: Copyright is fine the way it is> tagged "legal">',
  264. '<Tag: <Article: Django conquers world!> tagged "django">',
  265. '<Tag: <Article: Django conquers world!> tagged "world domination">',
  266. ],
  267. transform=repr,
  268. ordered=False,
  269. )
  270. # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany.
  271. management.call_command("loaddata", "fixture8.json", verbosity=0)
  272. self.assertQuerySetEqual(
  273. Visa.objects.all(),
  274. [
  275. "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
  276. "user>",
  277. "<Visa: Stephane Grappelli Can add user>",
  278. "<Visa: Prince >",
  279. ],
  280. transform=repr,
  281. ordered=False,
  282. )
  283. # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany.
  284. management.call_command("loaddata", "fixture9.xml", verbosity=0)
  285. self.assertQuerySetEqual(
  286. Visa.objects.all(),
  287. [
  288. "<Visa: Django Reinhardt Can add user, Can change user, Can delete "
  289. "user>",
  290. "<Visa: Stephane Grappelli Can add user, Can delete user>",
  291. '<Visa: Artist formerly known as "Prince" Can change user>',
  292. ],
  293. transform=repr,
  294. ordered=False,
  295. )
  296. # object list is unaffected
  297. self.assertSequenceEqual(
  298. Article.objects.values_list("headline", flat=True),
  299. [
  300. "XML identified as leading cause of cancer",
  301. "Django conquers world!",
  302. "Copyright is fine the way it is",
  303. "Poker on TV is great!",
  304. ],
  305. )
  306. # By default, you get raw keys on dumpdata
  307. self._dumpdata_assert(
  308. ["fixtures.book"],
  309. '[{"pk": 1, "model": "fixtures.book", "fields": '
  310. '{"name": "Music for all ages", "authors": [3, 1]}}]',
  311. )
  312. # But you can get natural keys if you ask for them and they are available
  313. self._dumpdata_assert(
  314. ["fixtures.book"],
  315. '[{"pk": 1, "model": "fixtures.book", "fields": '
  316. '{"name": "Music for all ages", "authors": '
  317. '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
  318. natural_foreign_keys=True,
  319. )
  320. # You can also omit the primary keys for models that we can get later
  321. # with natural keys.
  322. self._dumpdata_assert(
  323. ["fixtures.person"],
  324. '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, '
  325. '{"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, '
  326. '{"fields": {"name": "Artist formerly known as \\"Prince\\""}, '
  327. '"model": "fixtures.person"}]',
  328. natural_primary_keys=True,
  329. )
  330. # Dump the current contents of the database as a JSON fixture
  331. self._dumpdata_assert(
  332. ["fixtures"],
  333. '[{"pk": 1, "model": "fixtures.category", "fields": '
  334. '{"description": "Latest news stories", "title": "News Stories"}}, '
  335. '{"pk": 2, "model": "fixtures.article", "fields": '
  336. '{"headline": "Poker on TV is great!", '
  337. '"pub_date": "2006-06-16T11:00:00"}}, '
  338. '{"pk": 3, "model": "fixtures.article", "fields": '
  339. '{"headline": "Copyright is fine the way it is", '
  340. '"pub_date": "2006-06-16T14:00:00"}}, '
  341. '{"pk": 4, "model": "fixtures.article", "fields": '
  342. '{"headline": "Django conquers world!", '
  343. '"pub_date": "2006-06-16T15:00:00"}}, '
  344. '{"pk": 5, "model": "fixtures.article", "fields": '
  345. '{"headline": "XML identified as leading cause of cancer", '
  346. '"pub_date": "2006-06-16T16:00:00"}}, '
  347. '{"pk": 1, "model": "fixtures.tag", "fields": '
  348. '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
  349. '"tagged_id": 3}}, '
  350. '{"pk": 2, "model": "fixtures.tag", "fields": '
  351. '{"tagged_type": ["fixtures", "article"], "name": "legal", '
  352. '"tagged_id": 3}}, '
  353. '{"pk": 3, "model": "fixtures.tag", "fields": '
  354. '{"tagged_type": ["fixtures", "article"], "name": "django", '
  355. '"tagged_id": 4}}, '
  356. '{"pk": 4, "model": "fixtures.tag", "fields": '
  357. '{"tagged_type": ["fixtures", "article"], "name": "world domination", '
  358. '"tagged_id": 4}}, '
  359. '{"pk": 1, "model": "fixtures.person", '
  360. '"fields": {"name": "Django Reinhardt"}}, '
  361. '{"pk": 2, "model": "fixtures.person", '
  362. '"fields": {"name": "Stephane Grappelli"}}, '
  363. '{"pk": 3, "model": "fixtures.person", '
  364. '"fields": {"name": "Artist formerly known as \\"Prince\\""}}, '
  365. '{"pk": 1, "model": "fixtures.visa", '
  366. '"fields": {"person": ["Django Reinhardt"], "permissions": '
  367. '[["add_user", "auth", "user"], ["change_user", "auth", "user"], '
  368. '["delete_user", "auth", "user"]]}}, '
  369. '{"pk": 2, "model": "fixtures.visa", "fields": '
  370. '{"person": ["Stephane Grappelli"], "permissions": '
  371. '[["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, '
  372. '{"pk": 3, "model": "fixtures.visa", "fields": '
  373. '{"person": ["Artist formerly known as \\"Prince\\""], "permissions": '
  374. '[["change_user", "auth", "user"]]}}, '
  375. '{"pk": 1, "model": "fixtures.book", "fields": '
  376. '{"name": "Music for all ages", "authors": '
  377. '[["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]',
  378. natural_foreign_keys=True,
  379. )
  380. # Dump the current contents of the database as an XML fixture
  381. self._dumpdata_assert(
  382. ["fixtures"],
  383. '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
  384. '<object pk="1" model="fixtures.category">'
  385. '<field type="CharField" name="title">News Stories</field>'
  386. '<field type="TextField" name="description">Latest news stories</field>'
  387. "</object>"
  388. '<object pk="2" model="fixtures.article">'
  389. '<field type="CharField" name="headline">Poker on TV is great!</field>'
  390. '<field type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field>'
  391. "</object>"
  392. '<object pk="3" model="fixtures.article">'
  393. '<field type="CharField" name="headline">Copyright is fine the way it is'
  394. "</field>"
  395. '<field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field>'
  396. "</object>"
  397. '<object pk="4" model="fixtures.article">'
  398. '<field type="CharField" name="headline">Django conquers world!</field>'
  399. '<field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field>'
  400. "</object>"
  401. '<object pk="5" model="fixtures.article">'
  402. '<field type="CharField" name="headline">'
  403. "XML identified as leading cause of cancer</field>"
  404. '<field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field>'
  405. "</object>"
  406. '<object pk="1" model="fixtures.tag">'
  407. '<field type="CharField" name="name">copyright</field>'
  408. '<field to="contenttypes.contenttype" name="tagged_type" '
  409. 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
  410. "</field>"
  411. '<field type="PositiveIntegerField" name="tagged_id">3</field>'
  412. "</object>"
  413. '<object pk="2" model="fixtures.tag">'
  414. '<field type="CharField" name="name">legal</field>'
  415. '<field to="contenttypes.contenttype" name="tagged_type" '
  416. 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
  417. "</field>"
  418. '<field type="PositiveIntegerField" name="tagged_id">3</field></object>'
  419. '<object pk="3" model="fixtures.tag">'
  420. '<field type="CharField" name="name">django</field>'
  421. '<field to="contenttypes.contenttype" name="tagged_type" '
  422. 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
  423. "</field>"
  424. '<field type="PositiveIntegerField" name="tagged_id">4</field>'
  425. "</object>"
  426. '<object pk="4" model="fixtures.tag">'
  427. '<field type="CharField" name="name">world domination</field>'
  428. '<field to="contenttypes.contenttype" name="tagged_type" '
  429. 'rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural>'
  430. "</field>"
  431. '<field type="PositiveIntegerField" name="tagged_id">4</field>'
  432. "</object>"
  433. '<object pk="1" model="fixtures.person">'
  434. '<field type="CharField" name="name">Django Reinhardt</field>'
  435. "</object>"
  436. '<object pk="2" model="fixtures.person">'
  437. '<field type="CharField" name="name">Stephane Grappelli</field>'
  438. "</object>"
  439. '<object pk="3" model="fixtures.person">'
  440. '<field type="CharField" name="name">Artist formerly known as "Prince"'
  441. "</field>"
  442. "</object>"
  443. '<object pk="1" model="fixtures.visa">'
  444. '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
  445. "<natural>Django Reinhardt</natural></field>"
  446. '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
  447. "<object><natural>add_user</natural><natural>auth</natural>"
  448. "<natural>user</natural></object><object><natural>change_user</natural>"
  449. "<natural>auth</natural><natural>user</natural></object>"
  450. "<object><natural>delete_user</natural><natural>auth</natural>"
  451. "<natural>user</natural></object></field>"
  452. "</object>"
  453. '<object pk="2" model="fixtures.visa">'
  454. '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
  455. "<natural>Stephane Grappelli</natural></field>"
  456. '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
  457. "<object><natural>add_user</natural><natural>auth</natural>"
  458. "<natural>user</natural></object>"
  459. "<object><natural>delete_user</natural><natural>auth</natural>"
  460. "<natural>user</natural></object></field>"
  461. "</object>"
  462. '<object pk="3" model="fixtures.visa">'
  463. '<field to="fixtures.person" name="person" rel="ManyToOneRel">'
  464. '<natural>Artist formerly known as "Prince"</natural></field>'
  465. '<field to="auth.permission" name="permissions" rel="ManyToManyRel">'
  466. "<object><natural>change_user</natural><natural>auth</natural>"
  467. "<natural>user</natural></object></field>"
  468. "</object>"
  469. '<object pk="1" model="fixtures.book">'
  470. '<field type="CharField" name="name">Music for all ages</field>'
  471. '<field to="fixtures.person" name="authors" rel="ManyToManyRel">'
  472. '<object><natural>Artist formerly known as "Prince"</natural></object>'
  473. "<object><natural>Django Reinhardt</natural></object></field>"
  474. "</object></django-objects>",
  475. format="xml",
  476. natural_foreign_keys=True,
  477. )
  478. def test_dumpdata_with_excludes(self):
  479. # Load fixture1 which has a site, two articles, and a category
  480. Site.objects.all().delete()
  481. management.call_command("loaddata", "fixture1.json", verbosity=0)
  482. # Excluding fixtures app should only leave sites
  483. self._dumpdata_assert(
  484. ["sites", "fixtures"],
  485. '[{"pk": 1, "model": "sites.site", "fields": '
  486. '{"domain": "example.com", "name": "example.com"}}]',
  487. exclude_list=["fixtures"],
  488. )
  489. # Excluding fixtures.Article/Book should leave fixtures.Category
  490. self._dumpdata_assert(
  491. ["sites", "fixtures"],
  492. '[{"pk": 1, "model": "sites.site", '
  493. '"fields": {"domain": "example.com", "name": "example.com"}}, '
  494. '{"pk": 1, "model": "fixtures.category", "fields": '
  495. '{"description": "Latest news stories", "title": "News Stories"}}]',
  496. exclude_list=["fixtures.Article", "fixtures.Book"],
  497. )
  498. # Excluding fixtures and fixtures.Article/Book should be a no-op
  499. self._dumpdata_assert(
  500. ["sites", "fixtures"],
  501. '[{"pk": 1, "model": "sites.site", '
  502. '"fields": {"domain": "example.com", "name": "example.com"}}, '
  503. '{"pk": 1, "model": "fixtures.category", '
  504. '"fields": {"description": "Latest news stories", '
  505. '"title": "News Stories"}}]',
  506. exclude_list=["fixtures.Article", "fixtures.Book"],
  507. )
  508. # Excluding sites and fixtures.Article/Book should only leave fixtures.Category
  509. self._dumpdata_assert(
  510. ["sites", "fixtures"],
  511. '[{"pk": 1, "model": "fixtures.category", "fields": '
  512. '{"description": "Latest news stories", "title": "News Stories"}}]',
  513. exclude_list=["fixtures.Article", "fixtures.Book", "sites"],
  514. )
  515. # Excluding a bogus app should throw an error
  516. with self.assertRaisesMessage(
  517. management.CommandError, "No installed app with label 'foo_app'."
  518. ):
  519. self._dumpdata_assert(["fixtures", "sites"], "", exclude_list=["foo_app"])
  520. # Excluding a bogus model should throw an error
  521. with self.assertRaisesMessage(
  522. management.CommandError, "Unknown model: fixtures.FooModel"
  523. ):
  524. self._dumpdata_assert(
  525. ["fixtures", "sites"], "", exclude_list=["fixtures.FooModel"]
  526. )
  527. @unittest.skipIf(
  528. sys.platform == "win32", "Windows doesn't support '?' in filenames."
  529. )
  530. def test_load_fixture_with_special_characters(self):
  531. management.call_command("loaddata", "fixture_with[special]chars", verbosity=0)
  532. self.assertEqual(
  533. Article.objects.get().headline,
  534. "How To Deal With Special Characters",
  535. )
  536. def test_dumpdata_with_filtering_manager(self):
  537. spy1 = Spy.objects.create(name="Paul")
  538. spy2 = Spy.objects.create(name="Alex", cover_blown=True)
  539. self.assertSequenceEqual(Spy.objects.all(), [spy1])
  540. # Use the default manager
  541. self._dumpdata_assert(
  542. ["fixtures.Spy"],
  543. '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
  544. % spy1.pk,
  545. )
  546. # Dump using Django's base manager. Should return all objects,
  547. # even those normally filtered by the manager
  548. self._dumpdata_assert(
  549. ["fixtures.Spy"],
  550. '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, '
  551. '{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]'
  552. % (spy2.pk, spy1.pk),
  553. use_base_manager=True,
  554. )
  555. def test_dumpdata_with_pks(self):
  556. management.call_command("loaddata", "fixture1.json", verbosity=0)
  557. management.call_command("loaddata", "fixture2.json", verbosity=0)
  558. self._dumpdata_assert(
  559. ["fixtures.Article"],
  560. '[{"pk": 2, "model": "fixtures.article", '
  561. '"fields": {"headline": "Poker has no place on ESPN", '
  562. '"pub_date": "2006-06-16T12:00:00"}}, '
  563. '{"pk": 3, "model": "fixtures.article", "fields": '
  564. '{"headline": "Copyright is fine the way it is", '
  565. '"pub_date": "2006-06-16T14:00:00"}}]',
  566. primary_keys="2,3",
  567. )
  568. self._dumpdata_assert(
  569. ["fixtures.Article"],
  570. '[{"pk": 2, "model": "fixtures.article", '
  571. '"fields": {"headline": "Poker has no place on ESPN", '
  572. '"pub_date": "2006-06-16T12:00:00"}}]',
  573. primary_keys="2",
  574. )
  575. with self.assertRaisesMessage(
  576. management.CommandError, "You can only use --pks option with one model"
  577. ):
  578. self._dumpdata_assert(
  579. ["fixtures"],
  580. '[{"pk": 2, "model": "fixtures.article", "fields": '
  581. '{"headline": "Poker has no place on ESPN", '
  582. '"pub_date": "2006-06-16T12:00:00"}}, '
  583. '{"pk": 3, "model": "fixtures.article", "fields": '
  584. '{"headline": "Copyright is fine the way it is", '
  585. '"pub_date": "2006-06-16T14:00:00"}}]',
  586. primary_keys="2,3",
  587. )
  588. with self.assertRaisesMessage(
  589. management.CommandError, "You can only use --pks option with one model"
  590. ):
  591. self._dumpdata_assert(
  592. "",
  593. '[{"pk": 2, "model": "fixtures.article", "fields": '
  594. '{"headline": "Poker has no place on ESPN", '
  595. '"pub_date": "2006-06-16T12:00:00"}}, '
  596. '{"pk": 3, "model": "fixtures.article", "fields": '
  597. '{"headline": "Copyright is fine the way it is", '
  598. '"pub_date": "2006-06-16T14:00:00"}}]',
  599. primary_keys="2,3",
  600. )
  601. with self.assertRaisesMessage(
  602. management.CommandError, "You can only use --pks option with one model"
  603. ):
  604. self._dumpdata_assert(
  605. ["fixtures.Article", "fixtures.category"],
  606. '[{"pk": 2, "model": "fixtures.article", "fields": '
  607. '{"headline": "Poker has no place on ESPN", '
  608. '"pub_date": "2006-06-16T12:00:00"}}, '
  609. '{"pk": 3, "model": "fixtures.article", "fields": '
  610. '{"headline": "Copyright is fine the way it is", '
  611. '"pub_date": "2006-06-16T14:00:00"}}]',
  612. primary_keys="2,3",
  613. )
  614. def test_dumpdata_with_uuid_pks(self):
  615. m1 = PrimaryKeyUUIDModel.objects.create()
  616. m2 = PrimaryKeyUUIDModel.objects.create()
  617. output = StringIO()
  618. management.call_command(
  619. "dumpdata",
  620. "fixtures.PrimaryKeyUUIDModel",
  621. "--pks",
  622. ", ".join([str(m1.id), str(m2.id)]),
  623. stdout=output,
  624. )
  625. result = output.getvalue()
  626. self.assertIn('"pk": "%s"' % m1.id, result)
  627. self.assertIn('"pk": "%s"' % m2.id, result)
  628. def test_dumpdata_with_file_output(self):
  629. management.call_command("loaddata", "fixture1.json", verbosity=0)
  630. self._dumpdata_assert(
  631. ["fixtures"],
  632. '[{"pk": 1, "model": "fixtures.category", "fields": '
  633. '{"description": "Latest news stories", "title": "News Stories"}}, '
  634. '{"pk": 2, "model": "fixtures.article", "fields": '
  635. '{"headline": "Poker has no place on ESPN", '
  636. '"pub_date": "2006-06-16T12:00:00"}}, '
  637. '{"pk": 3, "model": "fixtures.article", "fields": '
  638. '{"headline": "Time to reform copyright", '
  639. '"pub_date": "2006-06-16T13:00:00"}}]',
  640. filename="dumpdata.json",
  641. )
  642. def test_dumpdata_with_file_gzip_output(self):
  643. management.call_command("loaddata", "fixture1.json", verbosity=0)
  644. self._dumpdata_assert(
  645. ["fixtures"],
  646. '[{"pk": 1, "model": "fixtures.category", "fields": '
  647. '{"description": "Latest news stories", "title": "News Stories"}}, '
  648. '{"pk": 2, "model": "fixtures.article", "fields": '
  649. '{"headline": "Poker has no place on ESPN", '
  650. '"pub_date": "2006-06-16T12:00:00"}}, '
  651. '{"pk": 3, "model": "fixtures.article", "fields": '
  652. '{"headline": "Time to reform copyright", '
  653. '"pub_date": "2006-06-16T13:00:00"}}]',
  654. filename="dumpdata.json.gz",
  655. )
  656. @unittest.skipUnless(HAS_BZ2, "No bz2 library detected.")
  657. def test_dumpdata_with_file_bz2_output(self):
  658. management.call_command("loaddata", "fixture1.json", verbosity=0)
  659. self._dumpdata_assert(
  660. ["fixtures"],
  661. '[{"pk": 1, "model": "fixtures.category", "fields": '
  662. '{"description": "Latest news stories", "title": "News Stories"}}, '
  663. '{"pk": 2, "model": "fixtures.article", "fields": '
  664. '{"headline": "Poker has no place on ESPN", '
  665. '"pub_date": "2006-06-16T12:00:00"}}, '
  666. '{"pk": 3, "model": "fixtures.article", "fields": '
  667. '{"headline": "Time to reform copyright", '
  668. '"pub_date": "2006-06-16T13:00:00"}}]',
  669. filename="dumpdata.json.bz2",
  670. )
  671. @unittest.skipUnless(HAS_LZMA, "No lzma library detected.")
  672. def test_dumpdata_with_file_lzma_output(self):
  673. management.call_command("loaddata", "fixture1.json", verbosity=0)
  674. self._dumpdata_assert(
  675. ["fixtures"],
  676. '[{"pk": 1, "model": "fixtures.category", "fields": '
  677. '{"description": "Latest news stories", "title": "News Stories"}}, '
  678. '{"pk": 2, "model": "fixtures.article", "fields": '
  679. '{"headline": "Poker has no place on ESPN", '
  680. '"pub_date": "2006-06-16T12:00:00"}}, '
  681. '{"pk": 3, "model": "fixtures.article", "fields": '
  682. '{"headline": "Time to reform copyright", '
  683. '"pub_date": "2006-06-16T13:00:00"}}]',
  684. filename="dumpdata.json.lzma",
  685. )
  686. @unittest.skipUnless(HAS_LZMA, "No lzma library detected.")
  687. def test_dumpdata_with_file_xz_output(self):
  688. management.call_command("loaddata", "fixture1.json", verbosity=0)
  689. self._dumpdata_assert(
  690. ["fixtures"],
  691. '[{"pk": 1, "model": "fixtures.category", "fields": '
  692. '{"description": "Latest news stories", "title": "News Stories"}}, '
  693. '{"pk": 2, "model": "fixtures.article", "fields": '
  694. '{"headline": "Poker has no place on ESPN", '
  695. '"pub_date": "2006-06-16T12:00:00"}}, '
  696. '{"pk": 3, "model": "fixtures.article", "fields": '
  697. '{"headline": "Time to reform copyright", '
  698. '"pub_date": "2006-06-16T13:00:00"}}]',
  699. filename="dumpdata.json.xz",
  700. )
  701. def test_dumpdata_with_file_zip_output(self):
  702. management.call_command("loaddata", "fixture1.json", verbosity=0)
  703. msg = "Unsupported file extension (.zip). Fixtures saved in 'dumpdata.json'."
  704. with self.assertWarnsMessage(RuntimeWarning, msg):
  705. self._dumpdata_assert(
  706. ["fixtures"],
  707. '[{"pk": 1, "model": "fixtures.category", "fields": '
  708. '{"description": "Latest news stories", "title": "News Stories"}}, '
  709. '{"pk": 2, "model": "fixtures.article", "fields": '
  710. '{"headline": "Poker has no place on ESPN", '
  711. '"pub_date": "2006-06-16T12:00:00"}}, '
  712. '{"pk": 3, "model": "fixtures.article", "fields": '
  713. '{"headline": "Time to reform copyright", '
  714. '"pub_date": "2006-06-16T13:00:00"}}]',
  715. filename="dumpdata.json.zip",
  716. )
  717. def test_dumpdata_progressbar(self):
  718. """
  719. Dumpdata shows a progress bar on the command line when --output is set,
  720. stdout is a tty, and verbosity > 0.
  721. """
  722. management.call_command("loaddata", "fixture1.json", verbosity=0)
  723. new_io = StringIO()
  724. new_io.isatty = lambda: True
  725. with NamedTemporaryFile() as file:
  726. options = {
  727. "format": "json",
  728. "stdout": new_io,
  729. "stderr": new_io,
  730. "output": file.name,
  731. }
  732. management.call_command("dumpdata", "fixtures", **options)
  733. self.assertTrue(
  734. new_io.getvalue().endswith(
  735. "[" + "." * ProgressBar.progress_width + "]\n"
  736. )
  737. )
  738. # Test no progress bar when verbosity = 0
  739. options["verbosity"] = 0
  740. new_io = StringIO()
  741. new_io.isatty = lambda: True
  742. options.update({"stdout": new_io, "stderr": new_io})
  743. management.call_command("dumpdata", "fixtures", **options)
  744. self.assertEqual(new_io.getvalue(), "")
  745. def test_dumpdata_proxy_without_concrete(self):
  746. """
  747. A warning is displayed if a proxy model is dumped without its concrete
  748. parent.
  749. """
  750. ProxySpy.objects.create(name="Paul")
  751. msg = "fixtures.ProxySpy is a proxy model and won't be serialized."
  752. with self.assertWarnsMessage(ProxyModelWarning, msg):
  753. self._dumpdata_assert(["fixtures.ProxySpy"], "[]")
  754. def test_dumpdata_proxy_with_concrete(self):
  755. """
  756. A warning isn't displayed if a proxy model is dumped with its concrete
  757. parent.
  758. """
  759. spy = ProxySpy.objects.create(name="Paul")
  760. with warnings.catch_warnings(record=True) as warning_list:
  761. warnings.simplefilter("always")
  762. self._dumpdata_assert(
  763. ["fixtures.ProxySpy", "fixtures.Spy"],
  764. '[{"pk": %d, "model": "fixtures.spy", '
  765. '"fields": {"cover_blown": false}}]' % spy.pk,
  766. )
  767. self.assertEqual(len(warning_list), 0)
  768. def test_compress_format_loading(self):
  769. # Load fixture 4 (compressed), using format specification
  770. management.call_command("loaddata", "fixture4.json", verbosity=0)
  771. self.assertEqual(Article.objects.get().headline, "Django pets kitten")
  772. def test_compressed_specified_loading(self):
  773. # Load fixture 5 (compressed), using format *and* compression specification
  774. management.call_command("loaddata", "fixture5.json.zip", verbosity=0)
  775. self.assertEqual(
  776. Article.objects.get().headline,
  777. "WoW subscribers now outnumber readers",
  778. )
  779. def test_compressed_loading(self):
  780. # Load fixture 5 (compressed), only compression specification
  781. management.call_command("loaddata", "fixture5.zip", verbosity=0)
  782. self.assertEqual(
  783. Article.objects.get().headline,
  784. "WoW subscribers now outnumber readers",
  785. )
  786. def test_compressed_loading_gzip(self):
  787. management.call_command("loaddata", "fixture5.json.gz", verbosity=0)
  788. self.assertEqual(
  789. Article.objects.get().headline,
  790. "WoW subscribers now outnumber readers",
  791. )
  792. @unittest.skipUnless(HAS_BZ2, "No bz2 library detected.")
  793. def test_compressed_loading_bz2(self):
  794. management.call_command("loaddata", "fixture5.json.bz2", verbosity=0)
  795. self.assertEqual(
  796. Article.objects.get().headline,
  797. "WoW subscribers now outnumber readers",
  798. )
  799. @unittest.skipUnless(HAS_LZMA, "No lzma library detected.")
  800. def test_compressed_loading_lzma(self):
  801. management.call_command("loaddata", "fixture5.json.lzma", verbosity=0)
  802. self.assertEqual(
  803. Article.objects.get().headline,
  804. "WoW subscribers now outnumber readers",
  805. )
  806. @unittest.skipUnless(HAS_LZMA, "No lzma library detected.")
  807. def test_compressed_loading_xz(self):
  808. management.call_command("loaddata", "fixture5.json.xz", verbosity=0)
  809. self.assertEqual(
  810. Article.objects.get().headline,
  811. "WoW subscribers now outnumber readers",
  812. )
  813. def test_ambiguous_compressed_fixture(self):
  814. # The name "fixture5" is ambiguous, so loading raises an error.
  815. msg = "Multiple fixtures named 'fixture5'"
  816. with self.assertRaisesMessage(management.CommandError, msg):
  817. management.call_command("loaddata", "fixture5", verbosity=0)
  818. def test_db_loading(self):
  819. # Load db fixtures 1 and 2. These will load using the 'default'
  820. # database identifier implicitly.
  821. management.call_command("loaddata", "db_fixture_1", verbosity=0)
  822. management.call_command("loaddata", "db_fixture_2", verbosity=0)
  823. self.assertSequenceEqual(
  824. Article.objects.values_list("headline", flat=True),
  825. [
  826. "Who needs more than one database?",
  827. "Who needs to use compressed data?",
  828. ],
  829. )
  830. def test_loaddata_error_message(self):
  831. """
  832. Loading a fixture which contains an invalid object outputs an error
  833. message which contains the pk of the object that triggered the error.
  834. """
  835. # MySQL needs a little prodding to reject invalid data.
  836. # This won't affect other tests because the database connection
  837. # is closed at the end of each test.
  838. if connection.vendor == "mysql":
  839. with connection.cursor() as cursor:
  840. cursor.execute("SET sql_mode = 'TRADITIONAL'")
  841. msg = "Could not load fixtures.Article(pk=1):"
  842. with self.assertRaisesMessage(IntegrityError, msg):
  843. management.call_command("loaddata", "invalid.json", verbosity=0)
  844. @skipUnlessDBFeature("prohibits_null_characters_in_text_exception")
  845. def test_loaddata_null_characters_on_postgresql(self):
  846. error, msg = connection.features.prohibits_null_characters_in_text_exception
  847. msg = f"Could not load fixtures.Article(pk=2): {msg}"
  848. with self.assertRaisesMessage(error, msg):
  849. management.call_command("loaddata", "null_character_in_field_value.json")
  850. def test_loaddata_app_option(self):
  851. with self.assertRaisesMessage(
  852. CommandError, "No fixture named 'db_fixture_1' found."
  853. ):
  854. management.call_command(
  855. "loaddata", "db_fixture_1", verbosity=0, app_label="someotherapp"
  856. )
  857. self.assertQuerySetEqual(Article.objects.all(), [])
  858. management.call_command(
  859. "loaddata", "db_fixture_1", verbosity=0, app_label="fixtures"
  860. )
  861. self.assertEqual(
  862. Article.objects.get().headline,
  863. "Who needs more than one database?",
  864. )
  865. def test_loaddata_verbosity_three(self):
  866. output = StringIO()
  867. management.call_command(
  868. "loaddata", "fixture1.json", verbosity=3, stdout=output, stderr=output
  869. )
  870. command_output = output.getvalue()
  871. self.assertIn(
  872. "\rProcessed 1 object(s).\rProcessed 2 object(s)."
  873. "\rProcessed 3 object(s).\rProcessed 4 object(s).\n",
  874. command_output,
  875. )
  876. def test_loading_using(self):
  877. # Load fixtures 1 and 2. These will load using the 'default' database
  878. # identifier explicitly.
  879. management.call_command(
  880. "loaddata", "db_fixture_1", verbosity=0, database="default"
  881. )
  882. management.call_command(
  883. "loaddata", "db_fixture_2", verbosity=0, database="default"
  884. )
  885. self.assertSequenceEqual(
  886. Article.objects.values_list("headline", flat=True),
  887. [
  888. "Who needs more than one database?",
  889. "Who needs to use compressed data?",
  890. ],
  891. )
  892. def test_unmatched_identifier_loading(self):
  893. # Db fixture 3 won't load because the database identifier doesn't
  894. # match.
  895. with self.assertRaisesMessage(
  896. CommandError, "No fixture named 'db_fixture_3' found."
  897. ):
  898. management.call_command("loaddata", "db_fixture_3", verbosity=0)
  899. with self.assertRaisesMessage(
  900. CommandError, "No fixture named 'db_fixture_3' found."
  901. ):
  902. management.call_command(
  903. "loaddata", "db_fixture_3", verbosity=0, database="default"
  904. )
  905. self.assertQuerySetEqual(Article.objects.all(), [])
  906. def test_output_formats(self):
  907. # Load back in fixture 1, we need the articles from it
  908. management.call_command("loaddata", "fixture1", verbosity=0)
  909. # Try to load fixture 6 using format discovery
  910. management.call_command("loaddata", "fixture6", verbosity=0)
  911. self.assertQuerySetEqual(
  912. Tag.objects.all(),
  913. [
  914. '<Tag: <Article: Time to reform copyright> tagged "copyright">',
  915. '<Tag: <Article: Time to reform copyright> tagged "law">',
  916. ],
  917. transform=repr,
  918. ordered=False,
  919. )
  920. # Dump the current contents of the database as a JSON fixture
  921. self._dumpdata_assert(
  922. ["fixtures"],
  923. '[{"pk": 1, "model": "fixtures.category", "fields": '
  924. '{"description": "Latest news stories", "title": "News Stories"}}, '
  925. '{"pk": 2, "model": "fixtures.article", "fields": '
  926. '{"headline": "Poker has no place on ESPN", '
  927. '"pub_date": "2006-06-16T12:00:00"}}, '
  928. '{"pk": 3, "model": "fixtures.article", "fields": '
  929. '{"headline": "Time to reform copyright", '
  930. '"pub_date": "2006-06-16T13:00:00"}}, '
  931. '{"pk": 1, "model": "fixtures.tag", "fields": '
  932. '{"tagged_type": ["fixtures", "article"], "name": "copyright", '
  933. '"tagged_id": 3}}, '
  934. '{"pk": 2, "model": "fixtures.tag", "fields": '
  935. '{"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, '
  936. '{"pk": 1, "model": "fixtures.person", "fields": '
  937. '{"name": "Django Reinhardt"}}, '
  938. '{"pk": 2, "model": "fixtures.person", "fields": '
  939. '{"name": "Stephane Grappelli"}}, '
  940. '{"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]',
  941. natural_foreign_keys=True,
  942. )
  943. # Dump the current contents of the database as an XML fixture
  944. self._dumpdata_assert(
  945. ["fixtures"],
  946. '<?xml version="1.0" encoding="utf-8"?><django-objects version="1.0">'
  947. '<object pk="1" model="fixtures.category">'
  948. '<field type="CharField" name="title">News Stories</field>'
  949. '<field type="TextField" name="description">Latest news stories</field>'
  950. "</object>"
  951. '<object pk="2" model="fixtures.article">'
  952. '<field type="CharField" name="headline">Poker has no place on ESPN</field>'
  953. '<field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field>'
  954. "</object>"
  955. '<object pk="3" model="fixtures.article">'
  956. '<field type="CharField" name="headline">Time to reform copyright</field>'
  957. '<field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field>'
  958. "</object>"
  959. '<object pk="1" model="fixtures.tag">'
  960. '<field type="CharField" name="name">copyright</field>'
  961. '<field to="contenttypes.contenttype" name="tagged_type" '
  962. 'rel="ManyToOneRel"><natural>fixtures</natural>'
  963. "<natural>article</natural></field>"
  964. '<field type="PositiveIntegerField" name="tagged_id">3</field>'
  965. "</object>"
  966. '<object pk="2" model="fixtures.tag">'
  967. '<field type="CharField" name="name">law</field>'
  968. '<field to="contenttypes.contenttype" name="tagged_type" '
  969. 'rel="ManyToOneRel"><natural>fixtures</natural>'
  970. "<natural>article</natural></field>"
  971. '<field type="PositiveIntegerField" name="tagged_id">3</field>'
  972. "</object>"
  973. '<object pk="1" model="fixtures.person">'
  974. '<field type="CharField" name="name">Django Reinhardt</field>'
  975. "</object>"
  976. '<object pk="2" model="fixtures.person">'
  977. '<field type="CharField" name="name">Stephane Grappelli</field>'
  978. "</object>"
  979. '<object pk="3" model="fixtures.person">'
  980. '<field type="CharField" name="name">Prince</field>'
  981. "</object></django-objects>",
  982. format="xml",
  983. natural_foreign_keys=True,
  984. )
  985. def test_loading_with_exclude_app(self):
  986. Site.objects.all().delete()
  987. management.call_command(
  988. "loaddata", "fixture1", exclude=["fixtures"], verbosity=0
  989. )
  990. self.assertFalse(Article.objects.exists())
  991. self.assertFalse(Category.objects.exists())
  992. self.assertEqual(Site.objects.get().domain, "example.com")
  993. def test_loading_with_exclude_model(self):
  994. Site.objects.all().delete()
  995. management.call_command(
  996. "loaddata", "fixture1", exclude=["fixtures.Article"], verbosity=0
  997. )
  998. self.assertFalse(Article.objects.exists())
  999. self.assertEqual(Category.objects.get().title, "News Stories")
  1000. self.assertEqual(Site.objects.get().domain, "example.com")
  1001. def test_exclude_option_errors(self):
  1002. """Excluding a bogus app or model should raise an error."""
  1003. msg = "No installed app with label 'foo_app'."
  1004. with self.assertRaisesMessage(management.CommandError, msg):
  1005. management.call_command(
  1006. "loaddata", "fixture1", exclude=["foo_app"], verbosity=0
  1007. )
  1008. msg = "Unknown model: fixtures.FooModel"
  1009. with self.assertRaisesMessage(management.CommandError, msg):
  1010. management.call_command(
  1011. "loaddata", "fixture1", exclude=["fixtures.FooModel"], verbosity=0
  1012. )
  1013. def test_stdin_without_format(self):
  1014. """Reading from stdin raises an error if format isn't specified."""
  1015. msg = "--format must be specified when reading from stdin."
  1016. with self.assertRaisesMessage(management.CommandError, msg):
  1017. management.call_command("loaddata", "-", verbosity=0)
  1018. def test_loading_stdin(self):
  1019. """Loading fixtures from stdin with json and xml."""
  1020. tests_dir = os.path.dirname(__file__)
  1021. fixture_json = os.path.join(tests_dir, "fixtures", "fixture1.json")
  1022. fixture_xml = os.path.join(tests_dir, "fixtures", "fixture3.xml")
  1023. with mock.patch(
  1024. "django.core.management.commands.loaddata.sys.stdin", open(fixture_json)
  1025. ):
  1026. management.call_command("loaddata", "--format=json", "-", verbosity=0)
  1027. self.assertSequenceEqual(
  1028. Article.objects.values_list("headline", flat=True),
  1029. ["Time to reform copyright", "Poker has no place on ESPN"],
  1030. )
  1031. with mock.patch(
  1032. "django.core.management.commands.loaddata.sys.stdin", open(fixture_xml)
  1033. ):
  1034. management.call_command("loaddata", "--format=xml", "-", verbosity=0)
  1035. self.assertSequenceEqual(
  1036. Article.objects.values_list("headline", flat=True),
  1037. [
  1038. "XML identified as leading cause of cancer",
  1039. "Time to reform copyright",
  1040. "Poker on TV is great!",
  1041. ],
  1042. )
  1043. class NonexistentFixtureTests(TestCase):
  1044. """
  1045. Custom class to limit fixture dirs.
  1046. """
  1047. def test_loaddata_not_existent_fixture_file(self):
  1048. stdout_output = StringIO()
  1049. with self.assertRaisesMessage(
  1050. CommandError, "No fixture named 'this_fixture_doesnt_exist' found."
  1051. ):
  1052. management.call_command(
  1053. "loaddata", "this_fixture_doesnt_exist", stdout=stdout_output
  1054. )
  1055. @mock.patch("django.db.connection.enable_constraint_checking")
  1056. @mock.patch("django.db.connection.disable_constraint_checking")
  1057. def test_nonexistent_fixture_no_constraint_checking(
  1058. self, disable_constraint_checking, enable_constraint_checking
  1059. ):
  1060. """
  1061. If no fixtures match the loaddata command, constraints checks on the
  1062. database shouldn't be disabled. This is performance critical on MSSQL.
  1063. """
  1064. with self.assertRaisesMessage(
  1065. CommandError, "No fixture named 'this_fixture_doesnt_exist' found."
  1066. ):
  1067. management.call_command(
  1068. "loaddata", "this_fixture_doesnt_exist", verbosity=0
  1069. )
  1070. disable_constraint_checking.assert_not_called()
  1071. enable_constraint_checking.assert_not_called()
  1072. class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
  1073. available_apps = [
  1074. "fixtures",
  1075. "django.contrib.sites",
  1076. ]
  1077. @skipUnlessDBFeature("supports_forward_references")
  1078. def test_format_discovery(self):
  1079. # Load fixture 1 again, using format discovery
  1080. management.call_command("loaddata", "fixture1", verbosity=0)
  1081. self.assertSequenceEqual(
  1082. Article.objects.values_list("headline", flat=True),
  1083. ["Time to reform copyright", "Poker has no place on ESPN"],
  1084. )
  1085. # Try to load fixture 2 using format discovery; this will fail
  1086. # because there are two fixture2's in the fixtures directory
  1087. msg = "Multiple fixtures named 'fixture2'"
  1088. with self.assertRaisesMessage(management.CommandError, msg):
  1089. management.call_command("loaddata", "fixture2", verbosity=0)
  1090. # object list is unaffected
  1091. self.assertSequenceEqual(
  1092. Article.objects.values_list("headline", flat=True),
  1093. ["Time to reform copyright", "Poker has no place on ESPN"],
  1094. )
  1095. # Dump the current contents of the database as a JSON fixture
  1096. self._dumpdata_assert(
  1097. ["fixtures"],
  1098. '[{"pk": 1, "model": "fixtures.category", "fields": '
  1099. '{"description": "Latest news stories", "title": "News Stories"}}, '
  1100. '{"pk": 2, "model": "fixtures.article", "fields": '
  1101. '{"headline": "Poker has no place on ESPN", '
  1102. '"pub_date": "2006-06-16T12:00:00"}}, '
  1103. '{"pk": 3, "model": "fixtures.article", "fields": '
  1104. '{"headline": "Time to reform copyright", '
  1105. '"pub_date": "2006-06-16T13:00:00"}}]',
  1106. )
  1107. # Load fixture 4 (compressed), using format discovery
  1108. management.call_command("loaddata", "fixture4", verbosity=0)
  1109. self.assertSequenceEqual(
  1110. Article.objects.values_list("headline", flat=True),
  1111. [
  1112. "Django pets kitten",
  1113. "Time to reform copyright",
  1114. "Poker has no place on ESPN",
  1115. ],
  1116. )
  1117. class ForwardReferenceTests(DumpDataAssertMixin, TestCase):
  1118. def test_forward_reference_fk(self):
  1119. management.call_command("loaddata", "forward_reference_fk.json", verbosity=0)
  1120. t1, t2 = NaturalKeyThing.objects.all()
  1121. self.assertEqual(t1.other_thing, t2)
  1122. self.assertEqual(t2.other_thing, t1)
  1123. self._dumpdata_assert(
  1124. ["fixtures"],
  1125. '[{"model": "fixtures.naturalkeything", "pk": 1, '
  1126. '"fields": {"key": "t1", "other_thing": 2, "other_things": []}}, '
  1127. '{"model": "fixtures.naturalkeything", "pk": 2, '
  1128. '"fields": {"key": "t2", "other_thing": 1, "other_things": []}}]',
  1129. )
  1130. def test_forward_reference_fk_natural_key(self):
  1131. management.call_command(
  1132. "loaddata",
  1133. "forward_reference_fk_natural_key.json",
  1134. verbosity=0,
  1135. )
  1136. t1, t2 = NaturalKeyThing.objects.all()
  1137. self.assertEqual(t1.other_thing, t2)
  1138. self.assertEqual(t2.other_thing, t1)
  1139. self._dumpdata_assert(
  1140. ["fixtures"],
  1141. '[{"model": "fixtures.naturalkeything", '
  1142. '"fields": {"key": "t1", "other_thing": ["t2"], "other_things": []}}, '
  1143. '{"model": "fixtures.naturalkeything", '
  1144. '"fields": {"key": "t2", "other_thing": ["t1"], "other_things": []}}]',
  1145. natural_primary_keys=True,
  1146. natural_foreign_keys=True,
  1147. )
  1148. def test_forward_reference_m2m(self):
  1149. management.call_command("loaddata", "forward_reference_m2m.json", verbosity=0)
  1150. self.assertEqual(NaturalKeyThing.objects.count(), 3)
  1151. t1 = NaturalKeyThing.objects.get_by_natural_key("t1")
  1152. self.assertSequenceEqual(
  1153. t1.other_things.order_by("key").values_list("key", flat=True),
  1154. ["t2", "t3"],
  1155. )
  1156. self._dumpdata_assert(
  1157. ["fixtures"],
  1158. '[{"model": "fixtures.naturalkeything", "pk": 1, '
  1159. '"fields": {"key": "t1", "other_thing": null, "other_things": [2, 3]}}, '
  1160. '{"model": "fixtures.naturalkeything", "pk": 2, '
  1161. '"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
  1162. '{"model": "fixtures.naturalkeything", "pk": 3, '
  1163. '"fields": {"key": "t3", "other_thing": null, "other_things": []}}]',
  1164. )
  1165. def test_forward_reference_m2m_natural_key(self):
  1166. management.call_command(
  1167. "loaddata",
  1168. "forward_reference_m2m_natural_key.json",
  1169. verbosity=0,
  1170. )
  1171. self.assertEqual(NaturalKeyThing.objects.count(), 3)
  1172. t1 = NaturalKeyThing.objects.get_by_natural_key("t1")
  1173. self.assertSequenceEqual(
  1174. t1.other_things.order_by("key").values_list("key", flat=True),
  1175. ["t2", "t3"],
  1176. )
  1177. self._dumpdata_assert(
  1178. ["fixtures"],
  1179. '[{"model": "fixtures.naturalkeything", '
  1180. '"fields": {"key": "t1", "other_thing": null, '
  1181. '"other_things": [["t2"], ["t3"]]}}, '
  1182. '{"model": "fixtures.naturalkeything", '
  1183. '"fields": {"key": "t2", "other_thing": null, "other_things": []}}, '
  1184. '{"model": "fixtures.naturalkeything", '
  1185. '"fields": {"key": "t3", "other_thing": null, "other_things": []}}]',
  1186. natural_primary_keys=True,
  1187. natural_foreign_keys=True,
  1188. )
  1189. class CircularReferenceTests(DumpDataAssertMixin, TestCase):
  1190. def test_circular_reference(self):
  1191. management.call_command("loaddata", "circular_reference.json", verbosity=0)
  1192. obj_a = CircularA.objects.get()
  1193. obj_b = CircularB.objects.get()
  1194. self.assertEqual(obj_a.obj, obj_b)
  1195. self.assertEqual(obj_b.obj, obj_a)
  1196. self._dumpdata_assert(
  1197. ["fixtures"],
  1198. '[{"model": "fixtures.circulara", "pk": 1, '
  1199. '"fields": {"key": "x", "obj": 1}}, '
  1200. '{"model": "fixtures.circularb", "pk": 1, '
  1201. '"fields": {"key": "y", "obj": 1}}]',
  1202. )
  1203. def test_circular_reference_natural_key(self):
  1204. management.call_command(
  1205. "loaddata",
  1206. "circular_reference_natural_key.json",
  1207. verbosity=0,
  1208. )
  1209. obj_a = CircularA.objects.get()
  1210. obj_b = CircularB.objects.get()
  1211. self.assertEqual(obj_a.obj, obj_b)
  1212. self.assertEqual(obj_b.obj, obj_a)
  1213. self._dumpdata_assert(
  1214. ["fixtures"],
  1215. '[{"model": "fixtures.circulara", '
  1216. '"fields": {"key": "x", "obj": ["y"]}}, '
  1217. '{"model": "fixtures.circularb", '
  1218. '"fields": {"key": "y", "obj": ["x"]}}]',
  1219. natural_primary_keys=True,
  1220. natural_foreign_keys=True,
  1221. )