如何在Django中使用`DEBUG = TRUE'运行测试

时间:2017-08-26 15:24:48

标签: python django pytest django-testing

我正在尝试为自定义错误页面视图编写测试: - 可以找到文档here

另外,对于编写测试用例,我已按照建议here包含这些网址: -

if settings.DEBUG:
    urlpatterns += [
        url(r'^404/$', page_not_found_view),
        url(r'^500/$', my_custom_error_view),
        url(r'^400/$', bad_request_view),
        url(r'^403/$', permission_denied_view),
    ]

handler404 = page_not_found_view
handler500 = my_custom_error_view
handler403 = permission_denied_view
handler400 = bad_request_view

和views.py是: -

def page_not_found_view(request):
    t = loader.get_template('error/HTTP404.html')
    html = html = t.render({})
    return HttpResponseNotFound(html)


def my_custom_error_view(request):
    t = loader.get_template('error/HTTP500.html')
    html = html = t.render({})
    return HttpResponseServerError(html)


def permission_denied_view(request):
    t = loader.get_template('error/HTTP403.html')
    html = html = t.render({})
    return HttpResponseForbidden(html)


def bad_request_view(request):
    t = loader.get_template('error/HTTP400.html')
    html = html = t.render({})
    return HttpResponseBadRequest(html)

当我手动点击网址时,我会收到正确的回复代码,例如访问500的{​​{1}},依此类推。 由于这些网址仅在/500默认情况下包含且测试用例在setting.DEBUG=True和模式中运行,因此我尝试使用DEFAULT=False装饰器覆盖它

我的test.py文件是: -

@override_settings

但是使用这个@override_settings(DEBUG=True) class ErroCodeUrl(TestCase): def test_400_error(self): response = self.client.get('/400/') self.assertEqual(response.status_code, 500) def test_403_error(self): response = self.client.get('/403/') self.assertEqual(response.status_code, 500) def test_404_error(self): response = self.client.get('/404/') self.assertEqual(response.status_code, 500) def test_500_error(self): response = self.client.get('/500/') self.assertEqual(response.status_code, 500) 没有任何区别,无论是否有相同的断言错误。我为每个测试获得 404状态代码

@override_settings: -     response = self.client.get(' / 500 /')     断言错误:404!= 500

test_500_error: -     response = self.client.get(' / 500 /')     断言错误:404!= 400

注意: - 相同的错误代码' 404 test_400_error DEBUG = False`。

1 个答案:

答案 0 :(得分:1)

这是一种测试你的500

的方法
from django.test import TestCase
from django.test.client import RequestFactory
from .views import my_custom_error_view

class TestMyErrorPages(TestCase):

    def test_error_handlers(self):
        factory = RequestFactory()
        request = factory.get('/')
        response = my_custom_error_view(request)
        self.assertEqual(response.status_code, 500)