2015-06-15 20:55:55 +08:00
|
|
|
from django.core.exceptions import PermissionDenied
|
|
|
|
from django.template.response import TemplateResponse
|
2016-06-23 22:30:07 +08:00
|
|
|
from django.test import SimpleTestCase, modify_settings, override_settings
|
2018-12-08 06:52:28 +08:00
|
|
|
from django.urls import path
|
2016-06-23 22:30:07 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class MiddlewareAccessingContent:
|
2016-06-23 22:30:07 +08:00
|
|
|
def __init__(self, get_response):
|
|
|
|
self.get_response = get_response
|
|
|
|
|
|
|
|
def __call__(self, request):
|
|
|
|
response = self.get_response(request)
|
|
|
|
# Response.content should be available in the middleware even with a
|
|
|
|
# TemplateResponse-based exception response.
|
|
|
|
assert response.content
|
|
|
|
return response
|
2015-06-15 20:55:55 +08:00
|
|
|
|
|
|
|
|
|
|
|
def template_response_error_handler(request, exception=None):
|
|
|
|
return TemplateResponse(request, "test_handler.html", status=403)
|
|
|
|
|
|
|
|
|
|
|
|
def permission_denied_view(request):
|
|
|
|
raise PermissionDenied
|
|
|
|
|
|
|
|
|
|
|
|
urlpatterns = [
|
2018-12-08 06:52:28 +08:00
|
|
|
path("", permission_denied_view),
|
2015-06-15 20:55:55 +08:00
|
|
|
]
|
|
|
|
|
|
|
|
handler403 = template_response_error_handler
|
|
|
|
|
|
|
|
|
|
|
|
@override_settings(ROOT_URLCONF="handlers.tests_custom_error_handlers")
|
2016-06-23 22:30:07 +08:00
|
|
|
@modify_settings(
|
|
|
|
MIDDLEWARE={
|
|
|
|
"append": "handlers.tests_custom_error_handlers.MiddlewareAccessingContent"
|
2022-02-04 03:24:19 +08:00
|
|
|
}
|
2016-06-23 22:30:07 +08:00
|
|
|
)
|
2015-06-15 20:55:55 +08:00
|
|
|
class CustomErrorHandlerTests(SimpleTestCase):
|
|
|
|
def test_handler_renders_template_response(self):
|
|
|
|
"""
|
|
|
|
BaseHandler should render TemplateResponse if necessary.
|
|
|
|
"""
|
|
|
|
response = self.client.get("/")
|
|
|
|
self.assertContains(response, "Error handler content", status_code=403)
|