2017-01-20 01:16:04 +08:00
|
|
|
from unittest import mock
|
|
|
|
|
2017-02-28 09:00:09 +08:00
|
|
|
from django.db import connections
|
|
|
|
from django.test import TestCase, TransactionTestCase, override_settings
|
2021-11-13 01:36:13 +08:00
|
|
|
from django.test.testcases import DatabaseOperationForbidden
|
2015-04-14 22:43:57 +08:00
|
|
|
|
2018-07-12 12:12:20 +08:00
|
|
|
from .models import Car
|
|
|
|
|
2015-04-14 22:43:57 +08:00
|
|
|
|
2018-12-06 04:21:09 +08:00
|
|
|
class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase):
|
2015-04-14 22:43:57 +08:00
|
|
|
"""
|
|
|
|
TransactionTestCase._fixture_teardown() inhibits the post_migrate signal
|
|
|
|
for test classes with serialized_rollback=True.
|
|
|
|
"""
|
|
|
|
available_apps = ['test_utils']
|
|
|
|
serialized_rollback = True
|
|
|
|
|
|
|
|
def setUp(self):
|
|
|
|
# self.available_apps must be None to test the serialized_rollback
|
|
|
|
# condition.
|
|
|
|
self.available_apps = None
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.available_apps = ['test_utils']
|
|
|
|
|
|
|
|
@mock.patch('django.test.testcases.call_command')
|
|
|
|
def test(self, call_command):
|
|
|
|
# with a mocked call_command(), this doesn't have any effect.
|
|
|
|
self._fixture_teardown()
|
|
|
|
call_command.assert_called_with(
|
|
|
|
'flush', interactive=False, allow_cascade=False,
|
|
|
|
reset_sequences=False, inhibit_post_migrate=True,
|
|
|
|
database='default', verbosity=0,
|
|
|
|
)
|
2017-02-28 09:00:09 +08:00
|
|
|
|
|
|
|
|
|
|
|
@override_settings(DEBUG=True) # Enable query logging for test_queries_cleared
|
2018-07-12 12:12:20 +08:00
|
|
|
class TransactionTestCaseDatabasesTests(TestCase):
|
2017-02-28 09:00:09 +08:00
|
|
|
available_apps = []
|
2018-07-12 12:12:20 +08:00
|
|
|
databases = {'default', 'other'}
|
2017-02-28 09:00:09 +08:00
|
|
|
|
|
|
|
def test_queries_cleared(self):
|
|
|
|
"""
|
|
|
|
TransactionTestCase._pre_setup() clears the connections' queries_log
|
|
|
|
so that it's less likely to overflow. An overflow causes
|
|
|
|
assertNumQueries() to fail.
|
|
|
|
"""
|
2019-12-21 03:49:56 +08:00
|
|
|
for alias in self.databases:
|
2017-02-28 09:00:09 +08:00
|
|
|
self.assertEqual(len(connections[alias].queries_log), 0, 'Failed for alias %s' % alias)
|
2018-07-12 12:12:20 +08:00
|
|
|
|
|
|
|
|
|
|
|
class DisallowedDatabaseQueriesTests(TransactionTestCase):
|
|
|
|
available_apps = ['test_utils']
|
|
|
|
|
|
|
|
def test_disallowed_database_queries(self):
|
|
|
|
message = (
|
|
|
|
"Database queries to 'other' are not allowed in this test. "
|
|
|
|
"Add 'other' to test_utils.test_transactiontestcase."
|
|
|
|
"DisallowedDatabaseQueriesTests.databases to ensure proper test "
|
|
|
|
"isolation and silence this failure."
|
|
|
|
)
|
2021-11-13 01:36:13 +08:00
|
|
|
with self.assertRaisesMessage(DatabaseOperationForbidden, message):
|
2018-07-12 12:12:20 +08:00
|
|
|
Car.objects.using('other').get()
|