| 1 |
import unittest |
| 2 |
|
| 3 |
from django.db import connection, connections, transaction |
| 4 |
from django.http import Http404 |
| 5 |
from django.test import TestCase, TransactionTestCase, override_settings |
| 6 |
from django.urls import path |
| 7 |
|
| 8 |
from rest_framework import status |
| 9 |
from rest_framework.exceptions import APIException |
| 10 |
from rest_framework.response import Response |
| 11 |
from rest_framework.test import APIRequestFactory |
| 12 |
from rest_framework.views import APIView, set_rollback |
| 13 |
from tests.models import BasicModel |
| 14 |
|
| 15 |
factory = APIRequestFactory() |
| 16 |
|
| 17 |
|
| 18 |
class BasicView(APIView): |
| 19 |
def post(self, request, *args, **kwargs): |
| 20 |
BasicModel.objects.create() |
| 21 |
return Response({'method': 'GET'}) |
| 22 |
|
| 23 |
|
| 24 |
class ErrorView(APIView): |
| 25 |
def post(self, request, *args, **kwargs): |
| 26 |
BasicModel.objects.create() |
| 27 |
raise Exception |
| 28 |
|
| 29 |
|
| 30 |
class APIExceptionView(APIView): |
| 31 |
def post(self, request, *args, **kwargs): |
| 32 |
BasicModel.objects.create() |
| 33 |
raise APIException |
| 34 |
|
| 35 |
|
| 36 |
class NonAtomicAPIExceptionView(APIView): |
| 37 |
@transaction.non_atomic_requests |
| 38 |
def dispatch(self, *args, **kwargs): |
| 39 |
return super().dispatch(*args, **kwargs) |
| 40 |
|
| 41 |
def get(self, request, *args, **kwargs): |
| 42 |
BasicModel.objects.all() |
| 43 |
raise Http404 |
| 44 |
|
| 45 |
|
| 46 |
urlpatterns = ( |
| 47 |
path('', NonAtomicAPIExceptionView.as_view()), |
| 48 |
) |
| 49 |
|
| 50 |
|
| 51 |
@unittest.skipUnless( |
| 52 |
connection.features.uses_savepoints, |
| 53 |
"'atomic' requires transactions and savepoints." |
| 54 |
) |
| 55 |
class DBTransactionTests(TestCase): |
| 56 |
def setUp(self): |
| 57 |
self.view = BasicView.as_view() |
| 58 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 59 |
|
| 60 |
def tearDown(self): |
| 61 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 62 |
|
| 63 |
def test_no_exception_commit_transaction(self): |
| 64 |
request = factory.post('/') |
| 65 |
|
| 66 |
with self.assertNumQueries(1): |
| 67 |
response = self.view(request) |
| 68 |
assert not transaction.get_rollback() |
| 69 |
assert response.status_code == status.HTTP_200_OK |
| 70 |
assert BasicModel.objects.count() == 1 |
| 71 |
|
| 72 |
|
| 73 |
@unittest.skipUnless( |
| 74 |
connection.features.uses_savepoints, |
| 75 |
"'atomic' requires transactions and savepoints." |
| 76 |
) |
| 77 |
class DBTransactionErrorTests(TestCase): |
| 78 |
def setUp(self): |
| 79 |
self.view = ErrorView.as_view() |
| 80 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 81 |
|
| 82 |
def tearDown(self): |
| 83 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 84 |
|
| 85 |
def test_generic_exception_delegate_transaction_management(self): |
| 86 |
""" |
| 87 |
Transaction is eventually managed by outer-most transaction atomic |
| 88 |
block. DRF do not try to interfere here. |
| 89 |
|
| 90 |
We let django deal with the transaction when it will catch the Exception. |
| 91 |
""" |
| 92 |
request = factory.post('/') |
| 93 |
with self.assertNumQueries(3): |
| 94 |
# 1 - begin savepoint |
| 95 |
# 2 - insert |
| 96 |
# 3 - release savepoint |
| 97 |
with transaction.atomic(): |
| 98 |
self.assertRaises(Exception, self.view, request) |
| 99 |
assert not transaction.get_rollback() |
| 100 |
assert BasicModel.objects.count() == 1 |
| 101 |
|
| 102 |
|
| 103 |
@unittest.skipUnless( |
| 104 |
connection.features.uses_savepoints, |
| 105 |
"'atomic' requires transactions and savepoints." |
| 106 |
) |
| 107 |
class DBTransactionAPIExceptionTests(TestCase): |
| 108 |
def setUp(self): |
| 109 |
self.view = APIExceptionView.as_view() |
| 110 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 111 |
|
| 112 |
def tearDown(self): |
| 113 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 114 |
|
| 115 |
def test_api_exception_rollback_transaction(self): |
| 116 |
""" |
| 117 |
Transaction is rollbacked by our transaction atomic block. |
| 118 |
""" |
| 119 |
request = factory.post('/') |
| 120 |
num_queries = 4 if connection.features.can_release_savepoints else 3 |
| 121 |
with self.assertNumQueries(num_queries): |
| 122 |
# 1 - begin savepoint |
| 123 |
# 2 - insert |
| 124 |
# 3 - rollback savepoint |
| 125 |
# 4 - release savepoint |
| 126 |
with transaction.atomic(): |
| 127 |
response = self.view(request) |
| 128 |
assert transaction.get_rollback() |
| 129 |
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 130 |
assert BasicModel.objects.count() == 0 |
| 131 |
|
| 132 |
|
| 133 |
@unittest.skipUnless( |
| 134 |
connection.features.uses_savepoints, |
| 135 |
"'atomic' requires transactions and savepoints." |
| 136 |
) |
| 137 |
class MultiDBTransactionAPIExceptionTests(TestCase): |
| 138 |
databases = '__all__' |
| 139 |
|
| 140 |
def setUp(self): |
| 141 |
self.view = APIExceptionView.as_view() |
| 142 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 143 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = True |
| 144 |
|
| 145 |
def tearDown(self): |
| 146 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 147 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = False |
| 148 |
|
| 149 |
def test_api_exception_rollback_transaction(self): |
| 150 |
""" |
| 151 |
Transaction is rollbacked by our transaction atomic block. |
| 152 |
""" |
| 153 |
request = factory.post('/') |
| 154 |
num_queries = 4 if connection.features.can_release_savepoints else 3 |
| 155 |
with self.assertNumQueries(num_queries): |
| 156 |
# 1 - begin savepoint |
| 157 |
# 2 - insert |
| 158 |
# 3 - rollback savepoint |
| 159 |
# 4 - release savepoint |
| 160 |
with transaction.atomic(), transaction.atomic(using='secondary'): |
| 161 |
response = self.view(request) |
| 162 |
assert transaction.get_rollback() |
| 163 |
assert transaction.get_rollback(using='secondary') |
| 164 |
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 165 |
assert BasicModel.objects.count() == 0 |
| 166 |
|
| 167 |
|
| 168 |
@unittest.skipUnless( |
| 169 |
connection.features.uses_savepoints, |
| 170 |
"'atomic' requires transactions and savepoints." |
| 171 |
) |
| 172 |
@override_settings(ROOT_URLCONF='tests.test_atomic_requests') |
| 173 |
class NonAtomicDBTransactionAPIExceptionTests(TransactionTestCase): |
| 174 |
def setUp(self): |
| 175 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 176 |
|
| 177 |
def tearDown(self): |
| 178 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 179 |
|
| 180 |
def test_api_exception_rollback_transaction_non_atomic_view(self): |
| 181 |
response = self.client.get('/') |
| 182 |
|
| 183 |
# without checking connection.in_atomic_block view raises 500 |
| 184 |
# due attempt to rollback without transaction |
| 185 |
assert response.status_code == status.HTTP_404_NOT_FOUND |
| 186 |
|
| 187 |
|
| 188 |
@unittest.skipUnless( |
| 189 |
connection.features.uses_savepoints, |
| 190 |
"'atomic' requires transactions and savepoints." |
| 191 |
) |
| 192 |
class SetRollbackTests(TestCase): |
| 193 |
def setUp(self): |
| 194 |
connections.databases['default']['ATOMIC_REQUESTS'] = True |
| 195 |
|
| 196 |
def tearDown(self): |
| 197 |
connections.databases['default']['ATOMIC_REQUESTS'] = False |
| 198 |
|
| 199 |
def test_marks_initialized_atomic_connection_for_rollback(self): |
| 200 |
with transaction.atomic(): |
| 201 |
set_rollback() |
| 202 |
assert transaction.get_rollback() |
| 203 |
|
| 204 |
|
| 205 |
class UninitializedSecondaryConnectionMixin: |
| 206 |
""" |
| 207 |
Remove the 'secondary' connection wrapper from the current thread for |
| 208 |
the duration of a test, restoring the original wrapper afterwards so |
| 209 |
Django's test-case connection patching still finds it at class cleanup. |
| 210 |
""" |
| 211 |
def setUp(self): |
| 212 |
super().setUp() |
| 213 |
self._saved_secondary = getattr(connections._connections, 'secondary', None) |
| 214 |
if self._saved_secondary is not None: |
| 215 |
delattr(connections._connections, 'secondary') |
| 216 |
|
| 217 |
def tearDown(self): |
| 218 |
stray = getattr(connections._connections, 'secondary', None) |
| 219 |
if stray is not None and stray is not self._saved_secondary: |
| 220 |
stray.close() |
| 221 |
if self._saved_secondary is not None: |
| 222 |
setattr(connections._connections, 'secondary', self._saved_secondary) |
| 223 |
super().tearDown() |
| 224 |
|
| 225 |
|
| 226 |
class SetRollbackUninitializedConnectionTests(UninitializedSecondaryConnectionMixin, TestCase): |
| 227 |
def setUp(self): |
| 228 |
super().setUp() |
| 229 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = True |
| 230 |
|
| 231 |
def tearDown(self): |
| 232 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = False |
| 233 |
super().tearDown() |
| 234 |
|
| 235 |
def test_does_not_initialize_unused_connections(self): |
| 236 |
set_rollback() |
| 237 |
assert not hasattr(connections._connections, 'secondary') |
| 238 |
|
| 239 |
|
| 240 |
class MultiDBUnusedConnectionAPIExceptionTests(UninitializedSecondaryConnectionMixin, TestCase): |
| 241 |
def setUp(self): |
| 242 |
super().setUp() |
| 243 |
self.view = APIExceptionView.as_view() |
| 244 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = True |
| 245 |
|
| 246 |
def tearDown(self): |
| 247 |
connections.databases['secondary']['ATOMIC_REQUESTS'] = False |
| 248 |
super().tearDown() |
| 249 |
|
| 250 |
def test_api_exception_leaves_unused_connection_uninitialized(self): |
| 251 |
request = factory.post('/') |
| 252 |
response = self.view(request) |
| 253 |
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR |
| 254 |
assert not hasattr(connections._connections, 'secondary') |