2
0

tests.py 33 KB

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