2012-09-05 45 views
3

我測試我的觀點裏,我需要把它發送到HttpResponse對象,以確保作爲我希望我的觀點是做計算之前作出一些斷言上下文字典。但我怎麼能斷言?下面是我試圖在視圖中做一個例子:Python的 - 如何嘲笑實例的視圖

# some_app/views.py 
def my_view(request): 
    context = RequestContext(request) 

    if request.GET.get('something'): 
     value = # calculate the value somehow 
     context.update(some_value=value) 

    elif request.GET.get('something_else'): 
     value = # calculate the value in other way 
     context.update(some_value=value) 
    # other stuff the view does 

    return render_to_response('some_template.html', context_instance=context) 

它發生,我認爲也許我可以修補的觀點有上下文實例:

# some_app/tests/unit/test_myview.py 
from some_app import views 
from mock import patch 
from django.test.client import RequestFactory 


class MyTest(TestCase): 
    def test_my_view(self): 
     request = RequestFactory().get('some_url', data={ 
      'param1': 'a', 
      'param2': 'b' 
     }) 
     with patch('some_app.views', [WHAT DO I INCLUDE HERE?]) as context: 
      # by now, <context> should be the context instance created in the view 
      response = views.my_view(request) 
      self.assertTrue(context['some_value']['value1']) 
      self.assertFalse(context['some_value']['value2']) 
      self.assertRaises(IndexError, some_function, 
           context['some_value']['value1']) 

,但我可以」我們走來了一個工作思路:(

有沒有什麼辦法,在我的測試,我可以有可用的我在視圖中創建上下文實例?

感謝您的幫助:)

附:在瀏覽器測試或檢查生成的HTML是不是在這種情況下:(選項

回答

1

你可以,如果你使用的是TemplateResponse通過response.context_data測試方面嘗試:

# some_app/views.py 
from django.template.response import TemplateResponse 

def my_view(request): 
    context = {} 

    if request.GET.get('something'): 
     value = # calculate the value somehow 
     context.update(some_value=value) 

    elif request.GET.get('something_else'): 
     value = # calculate the value in other way 
     context.update(some_value=value) 
    # other stuff the view does 

    return TemplateResponse(request, 'some_template.html', context) 

測試:

# some_app/tests/unit/test_myview.py 
from some_app import views 
from django.test.client import RequestFactory 

class MyTest(TestCase): 
    def test_my_view(self): 
     request = RequestFactory().get('some_url', data={ 
      'param1': 'a', 
      'param2': 'b' 
     }) 

     response = views.my_view(request) 
     self.assertTrue(response.context_data['some_value']['value1']) 
     self.assertFalse(response.context_data['some_value']['value2']) 
     self.assertRaises(IndexError, some_function, 
           response.context_data['some_value']['value1']) 
+0

AttributeError:'HttpResponse'對象沒有任何屬性'context_data' – Gerard

+0

您有權利使用'context_data'是'TemplateResponse'中的屬性,所以在您使用基於類的通用視圖時可用。 –

+0

I upda我的答案。 –