tests.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. from __future__ import unicode_literals
  2. import os
  3. import sys
  4. import tempfile
  5. import unittest
  6. import warnings
  7. from django.apps import apps
  8. from django.contrib.sites.models import Site
  9. from django.core import management
  10. from django.core.serializers.base import ProgressBar
  11. from django.db import IntegrityError, connection
  12. from django.test import (
  13. TestCase, TransactionTestCase, ignore_warnings, skipUnlessDBFeature,
  14. )
  15. from django.utils import six
  16. from django.utils.encoding import force_text
  17. from .models import Article, Spy, Tag, Visa
  18. class TestCaseFixtureLoadingTests(TestCase):
  19. fixtures = ['fixture1.json', 'fixture2.json']
  20. def testClassFixtures(self):
  21. "Check that test case has installed 3 fixture objects"
  22. self.assertEqual(Article.objects.count(), 3)
  23. self.assertQuerysetEqual(Article.objects.all(), [
  24. '<Article: Django conquers world!>',
  25. '<Article: Copyright is fine the way it is>',
  26. '<Article: Poker has no place on ESPN>',
  27. ])
  28. class SubclassTestCaseFixtureLoadingTests(TestCaseFixtureLoadingTests):
  29. """
  30. Make sure that subclasses can remove fixtures from parent class (#21089).
  31. """
  32. fixtures = []
  33. def testClassFixtures(self):
  34. "Check that there were no fixture objects installed"
  35. self.assertEqual(Article.objects.count(), 0)
  36. class DumpDataAssertMixin(object):
  37. def _dumpdata_assert(self, args, output, format='json', filename=None,
  38. natural_foreign_keys=False, natural_primary_keys=False,
  39. use_base_manager=False, exclude_list=[], primary_keys=''):
  40. new_io = six.StringIO()
  41. if filename:
  42. filename = os.path.join(tempfile.gettempdir(), filename)
  43. management.call_command('dumpdata', *args, **{'format': format,
  44. 'stdout': new_io,
  45. 'stderr': new_io,
  46. 'output': filename,
  47. 'use_natural_foreign_keys': natural_foreign_keys,
  48. 'use_natural_primary_keys': natural_primary_keys,
  49. 'use_base_manager': use_base_manager,
  50. 'exclude': exclude_list,
  51. 'primary_keys': primary_keys})
  52. if filename:
  53. with open(filename, "r") as f:
  54. command_output = f.read()
  55. os.remove(filename)
  56. else:
  57. command_output = new_io.getvalue().strip()
  58. if format == "json":
  59. self.assertJSONEqual(command_output, output)
  60. elif format == "xml":
  61. self.assertXMLEqual(command_output, output)
  62. else:
  63. self.assertEqual(command_output, output)
  64. class FixtureLoadingTests(DumpDataAssertMixin, TestCase):
  65. def test_loading_and_dumping(self):
  66. apps.clear_cache()
  67. Site.objects.all().delete()
  68. # Load fixture 1. Single JSON file, with two objects.
  69. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  70. self.assertQuerysetEqual(Article.objects.all(), [
  71. '<Article: Time to reform copyright>',
  72. '<Article: Poker has no place on ESPN>',
  73. ])
  74. # Dump the current contents of the database as a JSON fixture
  75. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  76. # Try just dumping the contents of fixtures.Category
  77. self._dumpdata_assert(['fixtures.Category'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]')
  78. # ...and just fixtures.Article
  79. self._dumpdata_assert(['fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  80. # ...and both
  81. self._dumpdata_assert(['fixtures.Category', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  82. # Specify a specific model twice
  83. self._dumpdata_assert(['fixtures.Article', 'fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  84. # Specify a dump that specifies Article both explicitly and implicitly
  85. self._dumpdata_assert(['fixtures.Article', 'fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  86. # Specify a dump that specifies Article both explicitly and implicitly,
  87. # but lists the app first (#22025).
  88. self._dumpdata_assert(['fixtures', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  89. # Same again, but specify in the reverse order
  90. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  91. # Specify one model from one application, and an entire other application.
  92. self._dumpdata_assert(['fixtures.Category', 'sites'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]')
  93. # Load fixture 2. JSON file imported by default. Overwrites some existing objects
  94. management.call_command('loaddata', 'fixture2.json', verbosity=0)
  95. self.assertQuerysetEqual(Article.objects.all(), [
  96. '<Article: Django conquers world!>',
  97. '<Article: Copyright is fine the way it is>',
  98. '<Article: Poker has no place on ESPN>',
  99. ])
  100. # Load fixture 3, XML format.
  101. management.call_command('loaddata', 'fixture3.xml', verbosity=0)
  102. self.assertQuerysetEqual(Article.objects.all(), [
  103. '<Article: XML identified as leading cause of cancer>',
  104. '<Article: Django conquers world!>',
  105. '<Article: Copyright is fine the way it is>',
  106. '<Article: Poker on TV is great!>',
  107. ])
  108. # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne.
  109. management.call_command('loaddata', 'fixture6.json', verbosity=0)
  110. self.assertQuerysetEqual(Tag.objects.all(), [
  111. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  112. '<Tag: <Article: Copyright is fine the way it is> tagged "law">',
  113. ], ordered=False)
  114. # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne.
  115. management.call_command('loaddata', 'fixture7.xml', verbosity=0)
  116. self.assertQuerysetEqual(Tag.objects.all(), [
  117. '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
  118. '<Tag: <Article: Copyright is fine the way it is> tagged "legal">',
  119. '<Tag: <Article: Django conquers world!> tagged "django">',
  120. '<Tag: <Article: Django conquers world!> tagged "world domination">',
  121. ], ordered=False)
  122. # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany.
  123. management.call_command('loaddata', 'fixture8.json', verbosity=0)
  124. self.assertQuerysetEqual(Visa.objects.all(), [
  125. '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
  126. '<Visa: Stephane Grappelli Can add user>',
  127. '<Visa: Prince >'
  128. ], ordered=False)
  129. # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany.
  130. management.call_command('loaddata', 'fixture9.xml', verbosity=0)
  131. self.assertQuerysetEqual(Visa.objects.all(), [
  132. '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
  133. '<Visa: Stephane Grappelli Can add user, Can delete user>',
  134. '<Visa: Artist formerly known as "Prince" Can change user>'
  135. ], ordered=False)
  136. # object list is unaffected
  137. self.assertQuerysetEqual(Article.objects.all(), [
  138. '<Article: XML identified as leading cause of cancer>',
  139. '<Article: Django conquers world!>',
  140. '<Article: Copyright is fine the way it is>',
  141. '<Article: Poker on TV is great!>',
  142. ])
  143. # By default, you get raw keys on dumpdata
  144. self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]')
  145. # But you can get natural keys if you ask for them and they are available
  146. self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True)
  147. # You can also omit the primary keys for models that we can get later with natural keys.
  148. self._dumpdata_assert(['fixtures.person'], '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as \\"Prince\\""}, "model": "fixtures.person"}]', natural_primary_keys=True)
  149. # Dump the current contents of the database as a JSON fixture
  150. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, "model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": "2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", "fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], ["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": "fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person": ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, {"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True)
  151. # Dump the current contents of the database as an XML fixture
  152. self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
  153. <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it is</field><field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field></object><object pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!</field><field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field></object><object pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag"><field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="1" model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as "Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object></django-objects>""", format='xml', natural_foreign_keys=True)
  154. def test_dumpdata_with_excludes(self):
  155. # Load fixture1 which has a site, two articles, and a category
  156. Site.objects.all().delete()
  157. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  158. # Excluding fixtures app should only leave sites
  159. self._dumpdata_assert(
  160. ['sites', 'fixtures'],
  161. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
  162. exclude_list=['fixtures'])
  163. # Excluding fixtures.Article/Book should leave fixtures.Category
  164. self._dumpdata_assert(
  165. ['sites', 'fixtures'],
  166. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]',
  167. exclude_list=['fixtures.Article', 'fixtures.Book'])
  168. # Excluding fixtures and fixtures.Article/Book should be a no-op
  169. self._dumpdata_assert(
  170. ['sites', 'fixtures'],
  171. '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}, {"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]',
  172. exclude_list=['fixtures.Article', 'fixtures.Book'])
  173. # Excluding sites and fixtures.Article/Book should only leave fixtures.Category
  174. self._dumpdata_assert(
  175. ['sites', 'fixtures'],
  176. '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]',
  177. exclude_list=['fixtures.Article', 'fixtures.Book', 'sites'])
  178. # Excluding a bogus app should throw an error
  179. with six.assertRaisesRegex(self, management.CommandError,
  180. "No installed app with label 'foo_app'."):
  181. self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['foo_app'])
  182. # Excluding a bogus model should throw an error
  183. with six.assertRaisesRegex(self, management.CommandError,
  184. "Unknown model in excludes: fixtures.FooModel"):
  185. self._dumpdata_assert(['fixtures', 'sites'], '', exclude_list=['fixtures.FooModel'])
  186. @unittest.skipIf(sys.platform.startswith('win'), "Windows doesn't support '?' in filenames.")
  187. def test_load_fixture_with_special_characters(self):
  188. management.call_command('loaddata', 'fixture_with[special]chars', verbosity=0)
  189. self.assertQuerysetEqual(Article.objects.all(), ['<Article: How To Deal With Special Characters>'])
  190. def test_dumpdata_with_filtering_manager(self):
  191. spy1 = Spy.objects.create(name='Paul')
  192. spy2 = Spy.objects.create(name='Alex', cover_blown=True)
  193. self.assertQuerysetEqual(Spy.objects.all(),
  194. ['<Spy: Paul>'])
  195. # Use the default manager
  196. self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
  197. # Dump using Django's base manager. Should return all objects,
  198. # even those normally filtered by the manager
  199. self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True)
  200. def test_dumpdata_with_pks(self):
  201. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  202. management.call_command('loaddata', 'fixture2.json', verbosity=0)
  203. self._dumpdata_assert(
  204. ['fixtures.Article'],
  205. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  206. primary_keys='2,3'
  207. )
  208. self._dumpdata_assert(
  209. ['fixtures.Article'],
  210. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}]',
  211. primary_keys='2'
  212. )
  213. with six.assertRaisesRegex(self, management.CommandError,
  214. "You can only use --pks option with one model"):
  215. self._dumpdata_assert(
  216. ['fixtures'],
  217. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  218. primary_keys='2,3'
  219. )
  220. with six.assertRaisesRegex(self, management.CommandError,
  221. "You can only use --pks option with one model"):
  222. self._dumpdata_assert(
  223. '',
  224. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  225. primary_keys='2,3'
  226. )
  227. with six.assertRaisesRegex(self, management.CommandError,
  228. "You can only use --pks option with one model"):
  229. self._dumpdata_assert(
  230. ['fixtures.Article', 'fixtures.category'],
  231. '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}]',
  232. primary_keys='2,3'
  233. )
  234. def test_dumpdata_with_file_output(self):
  235. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  236. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]',
  237. filename='dumpdata.json')
  238. def test_dumpdata_progressbar(self):
  239. """
  240. Dumpdata shows a progress bar on the command line when --output is set,
  241. stdout is a tty, and verbosity > 0.
  242. """
  243. management.call_command('loaddata', 'fixture1.json', verbosity=0)
  244. new_io = six.StringIO()
  245. new_io.isatty = lambda: True
  246. _, filename = tempfile.mkstemp()
  247. options = {
  248. 'format': 'json',
  249. 'stdout': new_io,
  250. 'stderr': new_io,
  251. 'output': filename,
  252. }
  253. management.call_command('dumpdata', 'fixtures', **options)
  254. self.assertTrue(new_io.getvalue().endswith('[' + '.' * ProgressBar.progress_width + ']\n'))
  255. # Test no progress bar when verbosity = 0
  256. options['verbosity'] = 0
  257. new_io = six.StringIO()
  258. new_io.isatty = lambda: True
  259. management.call_command('dumpdata', 'fixtures', **options)
  260. self.assertEqual(new_io.getvalue(), '')
  261. def test_compress_format_loading(self):
  262. # Load fixture 4 (compressed), using format specification
  263. management.call_command('loaddata', 'fixture4.json', verbosity=0)
  264. self.assertQuerysetEqual(Article.objects.all(), [
  265. '<Article: Django pets kitten>',
  266. ])
  267. def test_compressed_specified_loading(self):
  268. # Load fixture 5 (compressed), using format *and* compression specification
  269. management.call_command('loaddata', 'fixture5.json.zip', verbosity=0)
  270. self.assertQuerysetEqual(Article.objects.all(), [
  271. '<Article: WoW subscribers now outnumber readers>',
  272. ])
  273. def test_compressed_loading(self):
  274. # Load fixture 5 (compressed), only compression specification
  275. management.call_command('loaddata', 'fixture5.zip', verbosity=0)
  276. self.assertQuerysetEqual(Article.objects.all(), [
  277. '<Article: WoW subscribers now outnumber readers>',
  278. ])
  279. def test_ambiguous_compressed_fixture(self):
  280. # The name "fixture5" is ambiguous, so loading it will raise an error
  281. with self.assertRaises(management.CommandError) as cm:
  282. management.call_command('loaddata', 'fixture5', verbosity=0)
  283. self.assertIn("Multiple fixtures named 'fixture5'", cm.exception.args[0])
  284. def test_db_loading(self):
  285. # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
  286. management.call_command('loaddata', 'db_fixture_1', verbosity=0)
  287. management.call_command('loaddata', 'db_fixture_2', verbosity=0)
  288. self.assertQuerysetEqual(Article.objects.all(), [
  289. '<Article: Who needs more than one database?>',
  290. '<Article: Who needs to use compressed data?>',
  291. ])
  292. def test_loaddata_error_message(self):
  293. """
  294. Verifies that loading a fixture which contains an invalid object
  295. outputs an error message which contains the pk of the object
  296. that triggered the error.
  297. """
  298. # MySQL needs a little prodding to reject invalid data.
  299. # This won't affect other tests because the database connection
  300. # is closed at the end of each test.
  301. if connection.vendor == 'mysql':
  302. connection.cursor().execute("SET sql_mode = 'TRADITIONAL'")
  303. with self.assertRaises(IntegrityError) as cm:
  304. management.call_command('loaddata', 'invalid.json', verbosity=0)
  305. self.assertIn("Could not load fixtures.Article(pk=1):", cm.exception.args[0])
  306. @ignore_warnings(category=UserWarning, message="No fixture named")
  307. def test_loaddata_app_option(self):
  308. """
  309. Verifies that the --app option works.
  310. """
  311. management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="someotherapp")
  312. self.assertQuerysetEqual(Article.objects.all(), [])
  313. management.call_command('loaddata', 'db_fixture_1', verbosity=0, app_label="fixtures")
  314. self.assertQuerysetEqual(Article.objects.all(), [
  315. '<Article: Who needs more than one database?>',
  316. ])
  317. def test_loaddata_verbosity_three(self):
  318. output = six.StringIO()
  319. management.call_command('loaddata', 'fixture1.json', verbosity=3, stdout=output, stderr=output)
  320. command_output = force_text(output.getvalue())
  321. self.assertIn(
  322. "\rProcessed 1 object(s).\rProcessed 2 object(s)."
  323. "\rProcessed 3 object(s).\rProcessed 4 object(s).\n",
  324. command_output
  325. )
  326. def test_loading_using(self):
  327. # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
  328. management.call_command('loaddata', 'db_fixture_1', verbosity=0, using='default')
  329. management.call_command('loaddata', 'db_fixture_2', verbosity=0, using='default')
  330. self.assertQuerysetEqual(Article.objects.all(), [
  331. '<Article: Who needs more than one database?>',
  332. '<Article: Who needs to use compressed data?>',
  333. ])
  334. @ignore_warnings(category=UserWarning, message="No fixture named")
  335. def test_unmatched_identifier_loading(self):
  336. # Try to load db fixture 3. This won't load because the database identifier doesn't match
  337. management.call_command('loaddata', 'db_fixture_3', verbosity=0)
  338. management.call_command('loaddata', 'db_fixture_3', verbosity=0, using='default')
  339. self.assertQuerysetEqual(Article.objects.all(), [])
  340. def test_output_formats(self):
  341. # Load back in fixture 1, we need the articles from it
  342. management.call_command('loaddata', 'fixture1', verbosity=0)
  343. # Try to load fixture 6 using format discovery
  344. management.call_command('loaddata', 'fixture6', verbosity=0)
  345. self.assertQuerysetEqual(Tag.objects.all(), [
  346. '<Tag: <Article: Time to reform copyright> tagged "copyright">',
  347. '<Tag: <Article: Time to reform copyright> tagged "law">'
  348. ], ordered=False)
  349. # Dump the current contents of the database as a JSON fixture
  350. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "law", "tagged_id": 3}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}]', natural_foreign_keys=True)
  351. # Dump the current contents of the database as an XML fixture
  352. self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
  353. <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker has no place on ESPN</field><field type="DateTimeField" name="pub_date">2006-06-16T12:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16T13:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">law</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object></django-objects>""", format='xml', natural_foreign_keys=True)
  354. class NonExistentFixtureTests(TestCase):
  355. """
  356. Custom class to limit fixture dirs.
  357. """
  358. available_apps = ['django.contrib.auth', 'django.contrib.contenttypes']
  359. def test_loaddata_not_existent_fixture_file(self):
  360. stdout_output = six.StringIO()
  361. with warnings.catch_warnings(record=True) as w:
  362. warnings.simplefilter("always")
  363. # With verbosity=2, we get both stdout output and a warning
  364. management.call_command(
  365. 'loaddata',
  366. 'this_fixture_doesnt_exist',
  367. verbosity=2,
  368. stdout=stdout_output,
  369. )
  370. self.assertIn("No fixture 'this_fixture_doesnt_exist' in",
  371. force_text(stdout_output.getvalue()))
  372. self.assertEqual(len(w), 1)
  373. self.assertEqual(force_text(w[0].message),
  374. "No fixture named 'this_fixture_doesnt_exist' found.")
  375. class FixtureTransactionTests(DumpDataAssertMixin, TransactionTestCase):
  376. available_apps = [
  377. 'fixtures',
  378. 'django.contrib.contenttypes',
  379. 'django.contrib.auth',
  380. 'django.contrib.sites',
  381. ]
  382. @skipUnlessDBFeature('supports_forward_references')
  383. def test_format_discovery(self):
  384. # Load fixture 1 again, using format discovery
  385. management.call_command('loaddata', 'fixture1', verbosity=0)
  386. self.assertQuerysetEqual(Article.objects.all(), [
  387. '<Article: Time to reform copyright>',
  388. '<Article: Poker has no place on ESPN>',
  389. ])
  390. # Try to load fixture 2 using format discovery; this will fail
  391. # because there are two fixture2's in the fixtures directory
  392. with self.assertRaises(management.CommandError) as cm:
  393. management.call_command('loaddata', 'fixture2', verbosity=0)
  394. self.assertIn("Multiple fixtures named 'fixture2'", cm.exception.args[0])
  395. # object list is unaffected
  396. self.assertQuerysetEqual(Article.objects.all(), [
  397. '<Article: Time to reform copyright>',
  398. '<Article: Poker has no place on ESPN>',
  399. ])
  400. # Dump the current contents of the database as a JSON fixture
  401. self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]')
  402. # Load fixture 4 (compressed), using format discovery
  403. management.call_command('loaddata', 'fixture4', verbosity=0)
  404. self.assertQuerysetEqual(Article.objects.all(), [
  405. '<Article: Django pets kitten>',
  406. '<Article: Time to reform copyright>',
  407. '<Article: Poker has no place on ESPN>',
  408. ])