How to test 500.html error page in django development env?

后端 未结 10 1355
情话喂你
情话喂你 2020-12-28 13:00

I am using Django for a project and is already in production.

In the production environment 500.html is rendered whenever a server error occurs.

How do I tes

10条回答
  •  情书的邮戳
    2020-12-28 13:21

    urls.py

    handler500 = 'project.apps.core.views.handler500'
    handler404 = 'project.apps.core.views.handler404'
    

    views.py

    from django.template.loader import get_template
    from django.template import Context
    from django.http import HttpResponseServerError, HttpResponseNotFound
    
    
    def handler500(request, template_name='500.html'):
        t = get_template(template_name)
        ctx = Context({})
        return HttpResponseServerError(t.render(ctx))
    
    
    def handler404(request, template_name='404.html'):
        t = get_template(template_name)
        ctx = Context({})
        return HttpResponseNotFound(t.render(ctx))
    

    tests.py

    from django.test import TestCase
    from django.test.client import RequestFactory
    
    from project import urls
    
    from ..views import handler404, handler500
    
    
    class TestErrorPages(TestCase):
    
        def test_error_handlers(self):
            self.assertTrue(urls.handler404.endswith('.handler404'))
            self.assertTrue(urls.handler500.endswith('.handler500'))
            factory = RequestFactory()
            request = factory.get('/')
            response = handler404(request)
            self.assertEqual(response.status_code, 404)
            self.assertIn('404 Not Found!!', unicode(response))
            response = handler500(request)
            self.assertEqual(response.status_code, 500)
            self.assertIn('500 Internal Server Error', unicode(response))
    

提交回复
热议问题