tests.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. # -*- coding: utf-8 -*-
  2. # Unittests for fixtures.
  3. from __future__ import unicode_literals
  4. import os
  5. import re
  6. import warnings
  7. from django.core.serializers.base import DeserializationError
  8. from django.core import management
  9. from django.core.management.base import CommandError
  10. from django.core.management.commands.dumpdata import sort_dependencies
  11. from django.db import transaction, IntegrityError
  12. from django.db.models import signals
  13. from django.test import (TestCase, TransactionTestCase, skipIfDBFeature,
  14. skipUnlessDBFeature)
  15. from django.test.utils import override_settings
  16. from django.utils.encoding import force_text
  17. from django.utils._os import upath
  18. from django.utils import six
  19. from django.utils.six import PY3, StringIO
  20. import json
  21. from .models import (Animal, Stuff, Absolute, Parent, Child, Article, Widget,
  22. Store, Person, Book, NKChild, RefToNKChild, Circle1, Circle2, Circle3,
  23. ExternalDependency, Thingy)
  24. class TestFixtures(TestCase):
  25. def animal_pre_save_check(self, signal, sender, instance, **kwargs):
  26. self.pre_save_checks.append(
  27. (
  28. 'Count = %s (%s)' % (instance.count, type(instance.count)),
  29. 'Weight = %s (%s)' % (instance.weight, type(instance.weight)),
  30. )
  31. )
  32. def test_duplicate_pk(self):
  33. """
  34. This is a regression test for ticket #3790.
  35. """
  36. # Load a fixture that uses PK=1
  37. management.call_command(
  38. 'loaddata',
  39. 'sequence',
  40. verbosity=0,
  41. )
  42. # Create a new animal. Without a sequence reset, this new object
  43. # will take a PK of 1 (on Postgres), and the save will fail.
  44. animal = Animal(
  45. name='Platypus',
  46. latin_name='Ornithorhynchus anatinus',
  47. count=2,
  48. weight=2.2
  49. )
  50. animal.save()
  51. self.assertGreater(animal.id, 1)
  52. def test_loaddata_not_found_fields_not_ignore(self):
  53. """
  54. Test for ticket #9279 -- Error is raised for entries in
  55. the serialised data for fields that have been removed
  56. from the database when not ignored.
  57. """
  58. with self.assertRaises(DeserializationError):
  59. management.call_command(
  60. 'loaddata',
  61. 'sequence_extra',
  62. verbosity=0
  63. )
  64. def test_loaddata_not_found_fields_ignore(self):
  65. """
  66. Test for ticket #9279 -- Ignores entries in
  67. the serialised data for fields that have been removed
  68. from the database.
  69. """
  70. management.call_command(
  71. 'loaddata',
  72. 'sequence_extra',
  73. ignore=True,
  74. verbosity=0,
  75. )
  76. self.assertEqual(Animal.specimens.all()[0].name, 'Lion')
  77. def test_loaddata_not_found_fields_ignore_xml(self):
  78. """
  79. Test for ticket #19998 -- Ignore entries in the XML serialised data
  80. for fields that have been removed from the model definition.
  81. """
  82. management.call_command(
  83. 'loaddata',
  84. 'sequence_extra_xml',
  85. ignore=True,
  86. verbosity=0,
  87. )
  88. self.assertEqual(Animal.specimens.all()[0].name, 'Wolf')
  89. @skipIfDBFeature('interprets_empty_strings_as_nulls')
  90. def test_pretty_print_xml(self):
  91. """
  92. Regression test for ticket #4558 -- pretty printing of XML fixtures
  93. doesn't affect parsing of None values.
  94. """
  95. # Load a pretty-printed XML fixture with Nulls.
  96. management.call_command(
  97. 'loaddata',
  98. 'pretty.xml',
  99. verbosity=0,
  100. )
  101. self.assertEqual(Stuff.objects.all()[0].name, None)
  102. self.assertEqual(Stuff.objects.all()[0].owner, None)
  103. @skipUnlessDBFeature('interprets_empty_strings_as_nulls')
  104. def test_pretty_print_xml_empty_strings(self):
  105. """
  106. Regression test for ticket #4558 -- pretty printing of XML fixtures
  107. doesn't affect parsing of None values.
  108. """
  109. # Load a pretty-printed XML fixture with Nulls.
  110. management.call_command(
  111. 'loaddata',
  112. 'pretty.xml',
  113. verbosity=0,
  114. )
  115. self.assertEqual(Stuff.objects.all()[0].name, '')
  116. self.assertEqual(Stuff.objects.all()[0].owner, None)
  117. def test_absolute_path(self):
  118. """
  119. Regression test for ticket #6436 --
  120. os.path.join will throw away the initial parts of a path if it
  121. encounters an absolute path.
  122. This means that if a fixture is specified as an absolute path,
  123. we need to make sure we don't discover the absolute path in every
  124. fixture directory.
  125. """
  126. load_absolute_path = os.path.join(
  127. os.path.dirname(upath(__file__)),
  128. 'fixtures',
  129. 'absolute.json'
  130. )
  131. management.call_command(
  132. 'loaddata',
  133. load_absolute_path,
  134. verbosity=0,
  135. )
  136. self.assertEqual(Absolute.objects.count(), 1)
  137. def test_relative_path(self):
  138. directory = os.path.dirname(upath(__file__))
  139. relative_path = os.path.join('fixtures', 'absolute.json')
  140. cwd = os.getcwd()
  141. try:
  142. os.chdir(directory)
  143. management.call_command(
  144. 'loaddata',
  145. relative_path,
  146. verbosity=0,
  147. )
  148. finally:
  149. os.chdir(cwd)
  150. self.assertEqual(Absolute.objects.count(), 1)
  151. def test_unknown_format(self):
  152. """
  153. Test for ticket #4371 -- Loading data of an unknown format should fail
  154. Validate that error conditions are caught correctly
  155. """
  156. with six.assertRaisesRegex(self, management.CommandError,
  157. "Problem installing fixture 'bad_fixture1': "
  158. "unkn is not a known serialization format."):
  159. management.call_command(
  160. 'loaddata',
  161. 'bad_fixture1.unkn',
  162. verbosity=0,
  163. )
  164. @override_settings(SERIALIZATION_MODULES={'unkn': 'unexistent.path'})
  165. def test_unimportable_serializer(self):
  166. """
  167. Test that failing serializer import raises the proper error
  168. """
  169. with six.assertRaisesRegex(self, ImportError,
  170. r"No module named.*unexistent"):
  171. management.call_command(
  172. 'loaddata',
  173. 'bad_fixture1.unkn',
  174. verbosity=0,
  175. )
  176. def test_invalid_data(self):
  177. """
  178. Test for ticket #4371 -- Loading a fixture file with invalid data
  179. using explicit filename.
  180. Test for ticket #18213 -- warning conditions are caught correctly
  181. """
  182. with warnings.catch_warnings(record=True) as warning_list:
  183. warnings.simplefilter("always")
  184. management.call_command(
  185. 'loaddata',
  186. 'bad_fixture2.xml',
  187. verbosity=0,
  188. )
  189. warning = warning_list.pop()
  190. self.assertEqual(warning.category, RuntimeWarning)
  191. self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)")
  192. def test_invalid_data_no_ext(self):
  193. """
  194. Test for ticket #4371 -- Loading a fixture file with invalid data
  195. without file extension.
  196. Test for ticket #18213 -- warning conditions are caught correctly
  197. """
  198. with warnings.catch_warnings(record=True) as warning_list:
  199. warnings.simplefilter("always")
  200. management.call_command(
  201. 'loaddata',
  202. 'bad_fixture2',
  203. verbosity=0,
  204. )
  205. warning = warning_list.pop()
  206. self.assertEqual(warning.category, RuntimeWarning)
  207. self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)")
  208. def test_empty(self):
  209. """
  210. Test for ticket #18213 -- Loading a fixture file with no data output a warning.
  211. Previously empty fixture raises an error exception, see ticket #4371.
  212. """
  213. with warnings.catch_warnings(record=True) as warning_list:
  214. warnings.simplefilter("always")
  215. management.call_command(
  216. 'loaddata',
  217. 'empty',
  218. verbosity=0,
  219. )
  220. warning = warning_list.pop()
  221. self.assertEqual(warning.category, RuntimeWarning)
  222. self.assertEqual(str(warning.message), "No fixture data found for 'empty'. (File format may be invalid.)")
  223. def test_error_message(self):
  224. """
  225. Regression for #9011 - error message is correct.
  226. Change from error to warning for ticket #18213.
  227. """
  228. with warnings.catch_warnings(record=True) as warning_list:
  229. warnings.simplefilter("always")
  230. management.call_command(
  231. 'loaddata',
  232. 'bad_fixture2',
  233. 'animal',
  234. verbosity=0,
  235. )
  236. warning = warning_list.pop()
  237. self.assertEqual(warning.category, RuntimeWarning)
  238. self.assertEqual(str(warning.message), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)")
  239. def test_pg_sequence_resetting_checks(self):
  240. """
  241. Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn't
  242. ascend to parent models when inheritance is used
  243. (since they are treated individually).
  244. """
  245. management.call_command(
  246. 'loaddata',
  247. 'model-inheritance.json',
  248. verbosity=0,
  249. )
  250. self.assertEqual(Parent.objects.all()[0].id, 1)
  251. self.assertEqual(Child.objects.all()[0].id, 1)
  252. def test_close_connection_after_loaddata(self):
  253. """
  254. Test for ticket #7572 -- MySQL has a problem if the same connection is
  255. used to create tables, load data, and then query over that data.
  256. To compensate, we close the connection after running loaddata.
  257. This ensures that a new connection is opened when test queries are
  258. issued.
  259. """
  260. management.call_command(
  261. 'loaddata',
  262. 'big-fixture.json',
  263. verbosity=0,
  264. )
  265. articles = Article.objects.exclude(id=9)
  266. self.assertEqual(
  267. list(articles.values_list('id', flat=True)),
  268. [1, 2, 3, 4, 5, 6, 7, 8]
  269. )
  270. # Just for good measure, run the same query again.
  271. # Under the influence of ticket #7572, this will
  272. # give a different result to the previous call.
  273. self.assertEqual(
  274. list(articles.values_list('id', flat=True)),
  275. [1, 2, 3, 4, 5, 6, 7, 8]
  276. )
  277. def test_field_value_coerce(self):
  278. """
  279. Test for tickets #8298, #9942 - Field values should be coerced into the
  280. correct type by the deserializer, not as part of the database write.
  281. """
  282. self.pre_save_checks = []
  283. signals.pre_save.connect(self.animal_pre_save_check)
  284. try:
  285. management.call_command(
  286. 'loaddata',
  287. 'animal.xml',
  288. verbosity=0,
  289. )
  290. self.assertEqual(
  291. self.pre_save_checks,
  292. [
  293. ("Count = 42 (<%s 'int'>)" % ('class' if PY3 else 'type'),
  294. "Weight = 1.2 (<%s 'float'>)" % ('class' if PY3 else 'type'))
  295. ]
  296. )
  297. finally:
  298. signals.pre_save.disconnect(self.animal_pre_save_check)
  299. def test_dumpdata_uses_default_manager(self):
  300. """
  301. Regression for #11286
  302. Ensure that dumpdata honors the default manager
  303. Dump the current contents of the database as a JSON fixture
  304. """
  305. management.call_command(
  306. 'loaddata',
  307. 'animal.xml',
  308. verbosity=0,
  309. )
  310. management.call_command(
  311. 'loaddata',
  312. 'sequence.json',
  313. verbosity=0,
  314. )
  315. animal = Animal(
  316. name='Platypus',
  317. latin_name='Ornithorhynchus anatinus',
  318. count=2,
  319. weight=2.2
  320. )
  321. animal.save()
  322. stdout = StringIO()
  323. management.call_command(
  324. 'dumpdata',
  325. 'fixtures_regress.animal',
  326. format='json',
  327. stdout=stdout
  328. )
  329. # Output order isn't guaranteed, so check for parts
  330. data = stdout.getvalue()
  331. # Get rid of artifacts like '000000002' to eliminate the differences
  332. # between different Python versions.
  333. data = re.sub('0{6,}\d', '', data)
  334. animals_data = sorted([
  335. {"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}},
  336. {"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}},
  337. {"pk": animal.pk, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}},
  338. ], key=lambda x: x["pk"])
  339. data = sorted(json.loads(data), key=lambda x: x["pk"])
  340. self.maxDiff = 1024
  341. self.assertEqual(data, animals_data)
  342. def test_proxy_model_included(self):
  343. """
  344. Regression for #11428 - Proxy models aren't included when you dumpdata
  345. """
  346. stdout = StringIO()
  347. # Create an instance of the concrete class
  348. widget = Widget.objects.create(name='grommet')
  349. management.call_command(
  350. 'dumpdata',
  351. 'fixtures_regress.widget',
  352. 'fixtures_regress.widgetproxy',
  353. format='json',
  354. stdout=stdout
  355. )
  356. self.assertJSONEqual(
  357. stdout.getvalue(),
  358. """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
  359. % widget.pk
  360. )
  361. def test_loaddata_works_when_fixture_has_forward_refs(self):
  362. """
  363. Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)
  364. """
  365. management.call_command(
  366. 'loaddata',
  367. 'forward_ref.json',
  368. verbosity=0,
  369. )
  370. self.assertEqual(Book.objects.all()[0].id, 1)
  371. self.assertEqual(Person.objects.all()[0].id, 4)
  372. def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
  373. """
  374. Regression for #3615 - Ensure data with nonexistent child key references raises error
  375. """
  376. with six.assertRaisesRegex(self, IntegrityError,
  377. "Problem installing fixture"):
  378. management.call_command(
  379. 'loaddata',
  380. 'forward_ref_bad_data.json',
  381. verbosity=0,
  382. )
  383. _cur_dir = os.path.dirname(os.path.abspath(upath(__file__)))
  384. @override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, 'fixtures_1'),
  385. os.path.join(_cur_dir, 'fixtures_2')])
  386. def test_loaddata_forward_refs_split_fixtures(self):
  387. """
  388. Regression for #17530 - should be able to cope with forward references
  389. when the fixtures are not in the same files or directories.
  390. """
  391. management.call_command(
  392. 'loaddata',
  393. 'forward_ref_1.json',
  394. 'forward_ref_2.json',
  395. verbosity=0,
  396. )
  397. self.assertEqual(Book.objects.all()[0].id, 1)
  398. self.assertEqual(Person.objects.all()[0].id, 4)
  399. def test_loaddata_no_fixture_specified(self):
  400. """
  401. Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.
  402. """
  403. with six.assertRaisesRegex(self, management.CommandError,
  404. "No database fixture specified. Please provide the path of "
  405. "at least one fixture in the command line."):
  406. management.call_command(
  407. 'loaddata',
  408. verbosity=0,
  409. )
  410. def test_loaddata_not_existant_fixture_file(self):
  411. stdout_output = StringIO()
  412. with warnings.catch_warnings(record=True):
  413. management.call_command(
  414. 'loaddata',
  415. 'this_fixture_doesnt_exist',
  416. verbosity=2,
  417. stdout=stdout_output,
  418. )
  419. self.assertTrue("No fixture 'this_fixture_doesnt_exist' in" in
  420. force_text(stdout_output.getvalue()))
  421. def test_ticket_20820(self):
  422. """
  423. Regression for ticket #20820 -- loaddata on a model that inherits
  424. from a model with a M2M shouldn't blow up.
  425. """
  426. management.call_command(
  427. 'loaddata',
  428. 'special-article.json',
  429. verbosity=0,
  430. )
  431. class NaturalKeyFixtureTests(TestCase):
  432. def test_nk_deserialize(self):
  433. """
  434. Test for ticket #13030 - Python based parser version
  435. natural keys deserialize with fk to inheriting model
  436. """
  437. management.call_command(
  438. 'loaddata',
  439. 'model-inheritance.json',
  440. verbosity=0,
  441. )
  442. management.call_command(
  443. 'loaddata',
  444. 'nk-inheritance.json',
  445. verbosity=0,
  446. )
  447. self.assertEqual(
  448. NKChild.objects.get(pk=1).data,
  449. 'apple'
  450. )
  451. self.assertEqual(
  452. RefToNKChild.objects.get(pk=1).nk_fk.data,
  453. 'apple'
  454. )
  455. def test_nk_deserialize_xml(self):
  456. """
  457. Test for ticket #13030 - XML version
  458. natural keys deserialize with fk to inheriting model
  459. """
  460. management.call_command(
  461. 'loaddata',
  462. 'model-inheritance.json',
  463. verbosity=0,
  464. )
  465. management.call_command(
  466. 'loaddata',
  467. 'nk-inheritance.json',
  468. verbosity=0,
  469. )
  470. management.call_command(
  471. 'loaddata',
  472. 'nk-inheritance2.xml',
  473. verbosity=0,
  474. )
  475. self.assertEqual(
  476. NKChild.objects.get(pk=2).data,
  477. 'banana'
  478. )
  479. self.assertEqual(
  480. RefToNKChild.objects.get(pk=2).nk_fk.data,
  481. 'apple'
  482. )
  483. def test_nk_on_serialize(self):
  484. """
  485. Check that natural key requirements are taken into account
  486. when serializing models
  487. """
  488. management.call_command(
  489. 'loaddata',
  490. 'forward_ref_lookup.json',
  491. verbosity=0,
  492. )
  493. stdout = StringIO()
  494. management.call_command(
  495. 'dumpdata',
  496. 'fixtures_regress.book',
  497. 'fixtures_regress.person',
  498. 'fixtures_regress.store',
  499. verbosity=0,
  500. format='json',
  501. use_natural_foreign_keys=True,
  502. use_natural_primary_keys=True,
  503. stdout=stdout,
  504. )
  505. self.assertJSONEqual(
  506. stdout.getvalue(),
  507. """[{"fields": {"main": null, "name": "Amazon"}, "model": "fixtures_regress.store"}, {"fields": {"main": null, "name": "Borders"}, "model": "fixtures_regress.store"}, {"fields": {"name": "Neal Stephenson"}, "model": "fixtures_regress.person"}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]"""
  508. )
  509. def test_dependency_sorting(self):
  510. """
  511. Now lets check the dependency sorting explicitly
  512. It doesn't matter what order you mention the models
  513. Store *must* be serialized before then Person, and both
  514. must be serialized before Book.
  515. """
  516. sorted_deps = sort_dependencies(
  517. [('fixtures_regress', [Book, Person, Store])]
  518. )
  519. self.assertEqual(
  520. sorted_deps,
  521. [Store, Person, Book]
  522. )
  523. def test_dependency_sorting_2(self):
  524. sorted_deps = sort_dependencies(
  525. [('fixtures_regress', [Book, Store, Person])]
  526. )
  527. self.assertEqual(
  528. sorted_deps,
  529. [Store, Person, Book]
  530. )
  531. def test_dependency_sorting_3(self):
  532. sorted_deps = sort_dependencies(
  533. [('fixtures_regress', [Store, Book, Person])]
  534. )
  535. self.assertEqual(
  536. sorted_deps,
  537. [Store, Person, Book]
  538. )
  539. def test_dependency_sorting_4(self):
  540. sorted_deps = sort_dependencies(
  541. [('fixtures_regress', [Store, Person, Book])]
  542. )
  543. self.assertEqual(
  544. sorted_deps,
  545. [Store, Person, Book]
  546. )
  547. def test_dependency_sorting_5(self):
  548. sorted_deps = sort_dependencies(
  549. [('fixtures_regress', [Person, Book, Store])]
  550. )
  551. self.assertEqual(
  552. sorted_deps,
  553. [Store, Person, Book]
  554. )
  555. def test_dependency_sorting_6(self):
  556. sorted_deps = sort_dependencies(
  557. [('fixtures_regress', [Person, Store, Book])]
  558. )
  559. self.assertEqual(
  560. sorted_deps,
  561. [Store, Person, Book]
  562. )
  563. def test_dependency_sorting_dangling(self):
  564. sorted_deps = sort_dependencies(
  565. [('fixtures_regress', [Person, Circle1, Store, Book])]
  566. )
  567. self.assertEqual(
  568. sorted_deps,
  569. [Circle1, Store, Person, Book]
  570. )
  571. def test_dependency_sorting_tight_circular(self):
  572. self.assertRaisesMessage(
  573. CommandError,
  574. """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""",
  575. sort_dependencies,
  576. [('fixtures_regress', [Person, Circle2, Circle1, Store, Book])],
  577. )
  578. def test_dependency_sorting_tight_circular_2(self):
  579. self.assertRaisesMessage(
  580. CommandError,
  581. """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2 in serialized app list.""",
  582. sort_dependencies,
  583. [('fixtures_regress', [Circle1, Book, Circle2])],
  584. )
  585. def test_dependency_self_referential(self):
  586. self.assertRaisesMessage(
  587. CommandError,
  588. """Can't resolve dependencies for fixtures_regress.Circle3 in serialized app list.""",
  589. sort_dependencies,
  590. [('fixtures_regress', [Book, Circle3])],
  591. )
  592. def test_dependency_sorting_long(self):
  593. self.assertRaisesMessage(
  594. CommandError,
  595. """Can't resolve dependencies for fixtures_regress.Circle1, fixtures_regress.Circle2, fixtures_regress.Circle3 in serialized app list.""",
  596. sort_dependencies,
  597. [('fixtures_regress', [Person, Circle2, Circle1, Circle3, Store, Book])],
  598. )
  599. def test_dependency_sorting_normal(self):
  600. sorted_deps = sort_dependencies(
  601. [('fixtures_regress', [Person, ExternalDependency, Book])]
  602. )
  603. self.assertEqual(
  604. sorted_deps,
  605. [Person, Book, ExternalDependency]
  606. )
  607. def test_normal_pk(self):
  608. """
  609. Check that normal primary keys still work
  610. on a model with natural key capabilities
  611. """
  612. management.call_command(
  613. 'loaddata',
  614. 'non_natural_1.json',
  615. verbosity=0,
  616. )
  617. management.call_command(
  618. 'loaddata',
  619. 'forward_ref_lookup.json',
  620. verbosity=0,
  621. )
  622. management.call_command(
  623. 'loaddata',
  624. 'non_natural_2.xml',
  625. verbosity=0,
  626. )
  627. books = Book.objects.all()
  628. self.assertEqual(
  629. books.__repr__(),
  630. """[<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>, <Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>, <Book: Permutation City by Greg Egan (available at Angus and Robertson)>]"""
  631. )
  632. class TestTicket11101(TransactionTestCase):
  633. available_apps = [
  634. 'fixtures_regress',
  635. 'django.contrib.auth',
  636. 'django.contrib.contenttypes',
  637. ]
  638. @skipUnlessDBFeature('supports_transactions')
  639. def test_ticket_11101(self):
  640. """Test that fixtures can be rolled back (ticket #11101)."""
  641. with transaction.atomic():
  642. management.call_command(
  643. 'loaddata',
  644. 'thingy.json',
  645. verbosity=0,
  646. )
  647. self.assertEqual(Thingy.objects.count(), 1)
  648. transaction.set_rollback(True)
  649. self.assertEqual(Thingy.objects.count(), 0)