2017-08-26 43 views
0

我想寫我的自定義錯誤頁面視圖測試運行使用`DEBUG = TRUE`測試: - 文件可以發現here如何在Django

而且對於我已經包含了這些網址,編寫測試用例作爲建議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) 

當我打的網址手動我得到正確的[R例如500用於訪問/500等。 由於這些URL將被納入只有setting.DEBUG=True,缺省情況下DEFAULT=False和模式運行測試用例我嘗試使用@override_settings裝飾

我test.py文件來覆蓋它是: -

@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) 

但使用這@override_settings沒有任何區別我得到相同的斷言錯誤有或沒有它。我得到404狀態碼每一個測試即

對於test_500_error: - 響應= self.client.get( '/ 500 /') Asse田:404 = 500

對於test_400_error: - 響應= self.client.get( '/ 500 /') 的AssertionError:404 = 400

: - 相同的錯誤代碼「404 is returned when i visited these url with DEBUG = FALSE`。

+0

有你看看這個答案500 [https://stackoverflow.com/a/43139905/2581266] [ –

回答

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)