Debian Codegraph @

tests/test_utils/test_transactiontestcase.py

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