|
1 | 1 | from datetime import date
|
| 2 | +from unittest import mock |
2 | 3 |
|
| 4 | +from django.http import HttpResponse |
3 | 5 | from django.test import TestCase, override_settings
|
4 | 6 | from django.urls import reverse
|
5 | 7 |
|
| 8 | +from simple_history.models import HistoricalRecords |
6 | 9 | from simple_history.tests.custom_user.models import CustomUser
|
7 | 10 | from simple_history.tests.models import (
|
8 | 11 | BucketDataRegisterRequestUser,
|
@@ -146,6 +149,38 @@ def test_bucket_member_is_set_on_create_view_when_logged_in(self):
|
146 | 149 |
|
147 | 150 | self.assertListEqual([h.history_user_id for h in history], [member1.id])
|
148 | 151 |
|
| 152 | + # The `request` attribute of `HistoricalRecords.context` should be deleted |
| 153 | + # even if this setting is set to `True` |
| 154 | + @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) |
| 155 | + @mock.patch("simple_history.tests.view.MockableView.get") |
| 156 | + def test_request_attr_is_deleted_after_each_response(self, func_mock): |
| 157 | + """https://github.com/jazzband/django-simple-history/issues/1189""" |
| 158 | + |
| 159 | + def assert_has_request_attr(has_attr: bool): |
| 160 | + self.assertEqual(hasattr(HistoricalRecords.context, "request"), has_attr) |
| 161 | + |
| 162 | + def mocked_get(*args, **kwargs): |
| 163 | + assert_has_request_attr(True) |
| 164 | + response_ = HttpResponse(status=200) |
| 165 | + response_.historical_records_request = HistoricalRecords.context.request |
| 166 | + return response_ |
| 167 | + |
| 168 | + func_mock.side_effect = mocked_get |
| 169 | + self.client.force_login(self.user) |
| 170 | + mockable_url = reverse("mockable") |
| 171 | + |
| 172 | + assert_has_request_attr(False) |
| 173 | + response = self.client.get(mockable_url) |
| 174 | + assert_has_request_attr(False) |
| 175 | + # Check that the `request` attr existed while handling the request |
| 176 | + self.assertEqual(response.historical_records_request.user, self.user) |
| 177 | + |
| 178 | + func_mock.side_effect = RuntimeError() |
| 179 | + with self.assertRaises(RuntimeError): |
| 180 | + self.client.get(mockable_url) |
| 181 | + # The request variable should be deleted even if an exception was raised |
| 182 | + assert_has_request_attr(False) |
| 183 | + |
149 | 184 |
|
150 | 185 | @override_settings(**middleware_override_settings)
|
151 | 186 | class MiddlewareBulkOpsTest(TestCase):
|
|
0 commit comments