| 1 |
from django.core.exceptions import PermissionDenied |
| 2 |
from django.template.response import TemplateResponse |
| 3 |
from django.test import SimpleTestCase, modify_settings, override_settings |
| 4 |
from django.urls import path |
| 5 |
|
| 6 |
|
| 7 |
class MiddlewareAccessingContent: |
| 8 |
def __init__(self, get_response): |
| 9 |
self.get_response = get_response |
| 10 |
|
| 11 |
def __call__(self, request): |
| 12 |
response = self.get_response(request) |
| 13 |
# Response.content should be available in the middleware even with a |
| 14 |
# TemplateResponse-based exception response. |
| 15 |
assert response.content |
| 16 |
return response |
| 17 |
|
| 18 |
|
| 19 |
def template_response_error_handler(request, exception=None): |
| 20 |
return TemplateResponse(request, "test_handler.html", status=403) |
| 21 |
|
| 22 |
|
| 23 |
def permission_denied_view(request): |
| 24 |
raise PermissionDenied |
| 25 |
|
| 26 |
|
| 27 |
urlpatterns = [ |
| 28 |
path("", permission_denied_view), |
| 29 |
] |
| 30 |
|
| 31 |
handler403 = template_response_error_handler |
| 32 |
|
| 33 |
|
| 34 |
@override_settings(ROOT_URLCONF="handlers.tests_custom_error_handlers") |
| 35 |
@modify_settings( |
| 36 |
MIDDLEWARE={ |
| 37 |
"append": "handlers.tests_custom_error_handlers.MiddlewareAccessingContent" |
| 38 |
} |
| 39 |
) |
| 40 |
class CustomErrorHandlerTests(SimpleTestCase): |
| 41 |
def test_handler_renders_template_response(self): |
| 42 |
""" |
| 43 |
BaseHandler should render TemplateResponse if necessary. |
| 44 |
""" |
| 45 |
response = self.client.get("/") |
| 46 |
self.assertContains(response, "Error handler content", status_code=403) |