summaryrefslogtreecommitdiff
path: root/tests/test_utils/test_transactiontestcase.py
blob: 0032e2ee0c5fcf6810eff1ee6ff6e39be10b2507 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from unittest import mock

from django.db import connections
from django.test import TestCase, TransactionTestCase, override_settings
from django.test.testcases import DatabaseOperationForbidden

from .models import Car


class TestSerializedRollbackInhibitsPostMigrate(TransactionTestCase):
    """
    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,
        )


@override_settings(DEBUG=True)  # Enable query logging for test_queries_cleared
class TransactionTestCaseDatabasesTests(TestCase):
    available_apps = []
    databases = {"default", "other"}

    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.
        """
        for alias in self.databases:
            self.assertEqual(
                len(connections[alias].queries_log), 0, "Failed for alias %s" % alias
            )


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."
        )
        with self.assertRaisesMessage(DatabaseOperationForbidden, message):
            Car.objects.using("other").get()