tests.py 30 KB

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