test_transactiontestcase.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. from unittest import mock
  2. from django.db import connections
  3. from django.test import TestCase, TransactionTestCase, override_settings
  4. from django.test.testcases import DatabaseOperationForbidden
  5. from .models import Car, Person
  6. class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase):
  7. """
  8. TransactionTestCase._fixture_teardown() inhibits the post_migrate signal
  9. for test classes with serialized_rollback=True.
  10. """
  11. available_apps = ["test_utils"]
  12. serialized_rollback = True
  13. def setUp(self):
  14. # self.available_apps must be None to test the serialized_rollback
  15. # condition.
  16. self.available_apps = None
  17. def tearDown(self):
  18. self.available_apps = ["test_utils"]
  19. @mock.patch("django.test.testcases.call_command")
  20. def test(self, call_command):
  21. # with a mocked call_command(), this doesn't have any effect.
  22. self._fixture_teardown()
  23. call_command.assert_called_with(
  24. "flush",
  25. interactive=False,
  26. allow_cascade=False,
  27. reset_sequences=False,
  28. inhibit_post_migrate=True,
  29. database="default",
  30. verbosity=0,
  31. )
  32. @override_settings(DEBUG=True) # Enable query logging for test_queries_cleared
  33. class TransactionTestCaseDatabasesTests(TestCase):
  34. available_apps = []
  35. databases = {"default", "other"}
  36. def test_queries_cleared(self):
  37. """
  38. TransactionTestCase._pre_setup() clears the connections' queries_log
  39. so that it's less likely to overflow. An overflow causes
  40. assertNumQueries() to fail.
  41. """
  42. for alias in self.databases:
  43. self.assertEqual(
  44. len(connections[alias].queries_log), 0, "Failed for alias %s" % alias
  45. )
  46. class DisallowedDatabaseQueriesTests(TransactionTestCase):
  47. available_apps = ["test_utils"]
  48. def test_disallowed_database_queries(self):
  49. message = (
  50. "Database queries to 'other' are not allowed in this test. "
  51. "Add 'other' to test_utils.test_transactiontestcase."
  52. "DisallowedDatabaseQueriesTests.databases to ensure proper test "
  53. "isolation and silence this failure."
  54. )
  55. with self.assertRaisesMessage(DatabaseOperationForbidden, message):
  56. Car.objects.using("other").get()
  57. class FixtureAvailableInSetUpClassTest(TransactionTestCase):
  58. available_apps = ["test_utils"]
  59. fixtures = ["person.json"]
  60. @classmethod
  61. def setUpClass(cls):
  62. super().setUpClass()
  63. cls.elvis = Person.objects.get(name="Elvis Presley")
  64. def test_fixture_loaded_during_class_setup(self):
  65. self.assertIsInstance(self.elvis, Person)