Python - 如何在视图中模拟实例

时间:2012-09-05 21:09:39

标签: python django unit-testing mocking

我正在测试我的视图,我需要在将它发送到HttpResponse对象之前对上下文字典做一些断言,以确保我的视图按照我的预期进行计算。但我怎么能断言呢?以下是我在视图中尝试做的一个示例:

# 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'])

但我无法提出一个有用的想法:(

有没有办法,在我的测试中,我可以使用我在视图中创建的上下文实例?

感谢您的帮助:)

P.S。在这种情况下,浏览器内测试或检查生成的html不是一个选项:(

1 个答案:

答案 0 :(得分:1)

如果您使用response.context_data,则可以通过TemplateResponse测试上下文。尝试:

# 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'])