tests.py 35 KB

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