PageRenderTime 152ms CodeModel.GetById 44ms app.highlight 92ms RepoModel.GetById 7ms app.codeStats 0ms

/tests/modeltests/fixtures/tests.py

https://code.google.com/p/mango-py/
Python | 340 lines | 287 code | 31 blank | 22 comment | 0 complexity | 30f1a7a6c413bcc7e0b487187d7807f9 MD5 | raw file
  1import StringIO
  2import sys
  3
  4from django.conf import settings
  5from django.contrib.sites.models import Site
  6from django.core import management
  7from django.db import DEFAULT_DB_ALIAS
  8from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
  9
 10from models import Article, Blog, Book, Category, Person, Spy, Tag, Visa
 11
 12
 13class TestCaseFixtureLoadingTests(TestCase):
 14    fixtures = ['fixture1.json', 'fixture2.json']
 15
 16    def testClassFixtures(self):
 17        "Check that test case has installed 4 fixture objects"
 18        self.assertEqual(Article.objects.count(), 4)
 19        self.assertQuerysetEqual(Article.objects.all(), [
 20            '<Article: Django conquers world!>',
 21            '<Article: Copyright is fine the way it is>',
 22            '<Article: Poker has no place on ESPN>',
 23            '<Article: Python program becomes self aware>'
 24        ])
 25
 26class FixtureLoadingTests(TestCase):
 27
 28    def _dumpdata_assert(self, args, output, format='json', natural_keys=False,
 29                         use_base_manager=False, exclude_list=[]):
 30        new_io = StringIO.StringIO()
 31        management.call_command('dumpdata', *args, **{'format':format,
 32                                                      'stdout':new_io,
 33                                                      'stderr':new_io,
 34                                                      'use_natural_keys':natural_keys,
 35                                                      'use_base_manager':use_base_manager,
 36                                                      'exclude': exclude_list})
 37        command_output = new_io.getvalue().strip()
 38        self.assertEqual(command_output, output)
 39
 40    def test_initial_data(self):
 41        # Syncdb introduces 1 initial data object from initial_data.json.
 42        self.assertQuerysetEqual(Article.objects.all(), [
 43            '<Article: Python program becomes self aware>'
 44        ])
 45
 46    def test_loading_and_dumping(self):
 47        new_io = StringIO.StringIO()
 48
 49        Site.objects.all().delete()
 50        # Load fixture 1. Single JSON file, with two objects.
 51        management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
 52        self.assertQuerysetEqual(Article.objects.all(), [
 53            '<Article: Time to reform copyright>',
 54            '<Article: Poker has no place on ESPN>',
 55            '<Article: Python program becomes self aware>'
 56        ])
 57
 58        # Dump the current contents of the database as a JSON fixture
 59        self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 60
 61        # Try just dumping the contents of fixtures.Category
 62        self._dumpdata_assert(['fixtures.Category'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]')
 63
 64        # ...and just fixtures.Article
 65        self._dumpdata_assert(['fixtures.Article'], '[{"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 66
 67        # ...and both
 68        self._dumpdata_assert(['fixtures.Category', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 69
 70        # Specify a specific model twice
 71        self._dumpdata_assert(['fixtures.Article', 'fixtures.Article'], '[{"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 72
 73        # Specify a dump that specifies Article both explicitly and implicitly
 74        self._dumpdata_assert(['fixtures.Article', 'fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 75
 76        # Same again, but specify in the reverse order
 77        self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
 78
 79        # Specify one model from one application, and an entire other application.
 80        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"}}]')
 81
 82        # Load fixture 2. JSON file imported by default. Overwrites some existing objects
 83        management.call_command('loaddata', 'fixture2.json', verbosity=0, commit=False)
 84        self.assertQuerysetEqual(Article.objects.all(), [
 85            '<Article: Django conquers world!>',
 86            '<Article: Copyright is fine the way it is>',
 87            '<Article: Poker has no place on ESPN>',
 88            '<Article: Python program becomes self aware>'
 89        ])
 90
 91        # Load fixture 3, XML format.
 92        management.call_command('loaddata', 'fixture3.xml', verbosity=0, commit=False)
 93        self.assertQuerysetEqual(Article.objects.all(), [
 94            '<Article: XML identified as leading cause of cancer>',
 95            '<Article: Django conquers world!>',
 96            '<Article: Copyright is fine the way it is>',
 97            '<Article: Poker on TV is great!>',
 98            '<Article: Python program becomes self aware>'
 99        ])
100
101        # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne.
102        management.call_command('loaddata', 'fixture6.json', verbosity=0, commit=False)
103        self.assertQuerysetEqual(Tag.objects.all(), [
104            '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">',
105            '<Tag: <Article: Copyright is fine the way it is> tagged "law">'
106        ])
107
108        # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne.
109        management.call_command('loaddata', 'fixture7.xml', verbosity=0, commit=False)
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 "legal">',
113            '<Tag: <Article: Django conquers world!> tagged "django">',
114            '<Tag: <Article: Django conquers world!> tagged "world domination">'
115        ])
116
117        # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany.
118        management.call_command('loaddata', 'fixture8.json', verbosity=0, commit=False)
119        self.assertQuerysetEqual(Visa.objects.all(), [
120            '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
121            '<Visa: Stephane Grappelli Can add user>',
122            '<Visa: Prince >'
123        ])
124
125        # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany.
126        management.call_command('loaddata', 'fixture9.xml', verbosity=0, commit=False)
127        self.assertQuerysetEqual(Visa.objects.all(), [
128            '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>',
129            '<Visa: Stephane Grappelli Can add user, Can delete user>',
130            '<Visa: Artist formerly known as "Prince" Can change user>'
131        ])
132
133        self.assertQuerysetEqual(Book.objects.all(), [
134            '<Book: Music for all ages by Artist formerly known as "Prince" and Django Reinhardt>'
135        ])
136
137        # Load a fixture that doesn't exist
138        management.call_command('loaddata', 'unknown.json', verbosity=0, commit=False)
139
140        # object list is unaffected
141        self.assertQuerysetEqual(Article.objects.all(), [
142            '<Article: XML identified as leading cause of cancer>',
143            '<Article: Django conquers world!>',
144            '<Article: Copyright is fine the way it is>',
145            '<Article: Poker on TV is great!>',
146            '<Article: Python program becomes self aware>'
147        ])
148
149        # By default, you get raw keys on dumpdata
150        self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]')
151
152        # But you can get natural keys if you ask for them and they are available
153        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_keys=True)
154
155        # Dump the current contents of the database as a JSON fixture
156        self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML identified as leading cause of cancer", "pub_date": "2006-06-16 16:00:00"}}, {"pk": 4, "model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": "2006-06-16 15:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16 14:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is great!", "pub_date": "2006-06-16 11:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11: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": 3, "model": "fixtures.person", "fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"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_keys=True)
157
158        # Dump the current contents of the database as an XML fixture
159        self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
160<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="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-16 16: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-16 15: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-16 14:00:00</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-16 11:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11: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="3" model="fixtures.person"><field type="CharField" name="name">Artist formerly known as "Prince"</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="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_keys=True)
161
162    def test_dumpdata_with_excludes(self):
163        # Load fixture1 which has a site, two articles, and a category
164        Site.objects.all().delete()
165        management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
166
167        # Excluding fixtures app should only leave sites
168        self._dumpdata_assert(
169            ['sites', 'fixtures'],
170            '[{"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]',
171            exclude_list=['fixtures'])
172
173        # Excluding fixtures.Article should leave fixtures.Category
174        self._dumpdata_assert(
175            ['sites', 'fixtures'],
176            '[{"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"}}]',
177            exclude_list=['fixtures.Article'])
178
179        # Excluding fixtures and fixtures.Article should be a no-op
180        self._dumpdata_assert(
181            ['sites', 'fixtures'],
182            '[{"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"}}]',
183            exclude_list=['fixtures.Article'])
184
185        # Excluding sites and fixtures.Article should only leave fixtures.Category
186        self._dumpdata_assert(
187            ['sites', 'fixtures'],
188            '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]',
189            exclude_list=['fixtures.Article', 'sites'])
190
191        # Excluding a bogus app should throw an error
192        self.assertRaises(SystemExit,
193                          self._dumpdata_assert,
194                          ['fixtures', 'sites'],
195                          '',
196                          exclude_list=['foo_app'])
197
198        # Excluding a bogus model should throw an error
199        self.assertRaises(SystemExit,
200                          self._dumpdata_assert,
201                          ['fixtures', 'sites'],
202                          '',
203                          exclude_list=['fixtures.FooModel'])
204
205    def test_dumpdata_with_filtering_manager(self):
206        spy1 = Spy.objects.create(name='Paul')
207        spy2 = Spy.objects.create(name='Alex', cover_blown=True)
208        self.assertQuerysetEqual(Spy.objects.all(),
209                                 ['<Spy: Paul>'])
210        # Use the default manager
211        self._dumpdata_assert(['fixtures.Spy'],'[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
212        # Dump using Django's base manager. Should return all objects,
213        # even those normally filtered by the manager
214        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)
215
216    def test_compress_format_loading(self):
217        # Load fixture 4 (compressed), using format specification
218        management.call_command('loaddata', 'fixture4.json', verbosity=0, commit=False)
219        self.assertQuerysetEqual(Article.objects.all(), [
220            '<Article: Django pets kitten>',
221            '<Article: Python program becomes self aware>'
222        ])
223
224    def test_compressed_specified_loading(self):
225        # Load fixture 5 (compressed), using format *and* compression specification
226        management.call_command('loaddata', 'fixture5.json.zip', verbosity=0, commit=False)
227        self.assertQuerysetEqual(Article.objects.all(), [
228            '<Article: WoW subscribers now outnumber readers>',
229            '<Article: Python program becomes self aware>'
230        ])
231
232    def test_compressed_loading(self):
233        # Load fixture 5 (compressed), only compression specification
234        management.call_command('loaddata', 'fixture5.zip', verbosity=0, commit=False)
235        self.assertQuerysetEqual(Article.objects.all(), [
236            '<Article: WoW subscribers now outnumber readers>',
237            '<Article: Python program becomes self aware>'
238        ])
239
240    def test_ambiguous_compressed_fixture(self):
241        # The name "fixture5" is ambigous, so loading it will raise an error
242        new_io = StringIO.StringIO()
243        management.call_command('loaddata', 'fixture5', verbosity=0, stderr=new_io, commit=False)
244        output = new_io.getvalue().strip().split('\n')
245        self.assertEqual(len(output), 1)
246        self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture5'"))
247
248    def test_db_loading(self):
249        # Load db fixtures 1 and 2. These will load using the 'default' database identifier implicitly
250        management.call_command('loaddata', 'db_fixture_1', verbosity=0, commit=False)
251        management.call_command('loaddata', 'db_fixture_2', verbosity=0, commit=False)
252        self.assertQuerysetEqual(Article.objects.all(), [
253            '<Article: Who needs more than one database?>',
254            '<Article: Who needs to use compressed data?>',
255            '<Article: Python program becomes self aware>'
256        ])
257
258    def test_loading_using(self):
259        # Load db fixtures 1 and 2. These will load using the 'default' database identifier explicitly
260        management.call_command('loaddata', 'db_fixture_1', verbosity=0, using='default', commit=False)
261        management.call_command('loaddata', 'db_fixture_2', verbosity=0, using='default', commit=False)
262        self.assertQuerysetEqual(Article.objects.all(), [
263            '<Article: Who needs more than one database?>',
264            '<Article: Who needs to use compressed data?>',
265            '<Article: Python program becomes self aware>'
266        ])
267
268    def test_unmatched_identifier_loading(self):
269        # Try to load db fixture 3. This won't load because the database identifier doesn't match
270        management.call_command('loaddata', 'db_fixture_3', verbosity=0, commit=False)
271        self.assertQuerysetEqual(Article.objects.all(), [
272            '<Article: Python program becomes self aware>'
273        ])
274
275        management.call_command('loaddata', 'db_fixture_3', verbosity=0, using='default', commit=False)
276        self.assertQuerysetEqual(Article.objects.all(), [
277            '<Article: Python program becomes self aware>'
278        ])
279
280    def test_output_formats(self):
281        # Load back in fixture 1, we need the articles from it
282        management.call_command('loaddata', 'fixture1', verbosity=0, commit=False)
283
284        # Try to load fixture 6 using format discovery
285        management.call_command('loaddata', 'fixture6', verbosity=0, commit=False)
286        self.assertQuerysetEqual(Tag.objects.all(), [
287            '<Tag: <Article: Time to reform copyright> tagged "copyright">',
288            '<Tag: <Article: Time to reform copyright> tagged "law">'
289        ])
290
291        # Dump the current contents of the database as a JSON fixture
292        self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11: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": 3, "model": "fixtures.person", "fields": {"name": "Prince"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}]', natural_keys=True)
293
294        # Dump the current contents of the database as an XML fixture
295        self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?>
296<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="3" model="fixtures.article"><field type="CharField" name="headline">Time to reform copyright</field><field type="DateTimeField" name="pub_date">2006-06-16 13:00:00</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-16 12:00:00</field></object><object pk="1" model="fixtures.article"><field type="CharField" name="headline">Python program becomes self aware</field><field type="DateTimeField" name="pub_date">2006-06-16 11: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="3" model="fixtures.person"><field type="CharField" name="name">Prince</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object></django-objects>""", format='xml', natural_keys=True)
297
298class FixtureTransactionTests(TransactionTestCase):
299    def _dumpdata_assert(self, args, output, format='json'):
300        new_io = StringIO.StringIO()
301        management.call_command('dumpdata', *args, **{'format':format, 'stdout':new_io})
302        command_output = new_io.getvalue().strip()
303        self.assertEqual(command_output, output)
304
305    @skipUnlessDBFeature('supports_forward_references')
306    def test_format_discovery(self):
307        # Load fixture 1 again, using format discovery
308        management.call_command('loaddata', 'fixture1', verbosity=0, commit=False)
309        self.assertQuerysetEqual(Article.objects.all(), [
310            '<Article: Time to reform copyright>',
311            '<Article: Poker has no place on ESPN>',
312            '<Article: Python program becomes self aware>'
313        ])
314
315        # Try to load fixture 2 using format discovery; this will fail
316        # because there are two fixture2's in the fixtures directory
317        new_io = StringIO.StringIO()
318        management.call_command('loaddata', 'fixture2', verbosity=0, stderr=new_io)
319        output = new_io.getvalue().strip().split('\n')
320        self.assertEqual(len(output), 1)
321        self.assertTrue(output[0].startswith("Multiple fixtures named 'fixture2'"))
322
323        # object list is unaffected
324        self.assertQuerysetEqual(Article.objects.all(), [
325            '<Article: Time to reform copyright>',
326            '<Article: Poker has no place on ESPN>',
327            '<Article: Python program becomes self aware>'
328        ])
329
330        # Dump the current contents of the database as a JSON fixture
331        self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16 13:00:00"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16 12:00:00"}}, {"pk": 1, "model": "fixtures.article", "fields": {"headline": "Python program becomes self aware", "pub_date": "2006-06-16 11:00:00"}}]')
332
333        # Load fixture 4 (compressed), using format discovery
334        management.call_command('loaddata', 'fixture4', verbosity=0, commit=False)
335        self.assertQuerysetEqual(Article.objects.all(), [
336            '<Article: Django pets kitten>',
337            '<Article: Time to reform copyright>',
338            '<Article: Poker has no place on ESPN>',
339            '<Article: Python program becomes self aware>'
340        ])