tests.py 22 KB

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