使用 Mock 修补 render_to_response

发布于 2024-11-08 22:26:54 字数 1173 浏览 0 评论 0原文

我正在使用 Mock 并且我无法正确修补 django 的 render_to_response 函数。例如,以下测试永远不会失败:

    from django.test.client import Client
    from mock import patch
    import nose.tools as nt

    @patch('django.shortcuts.render_to_response')
    def test_should_fail(self, render_to_response):
        def assert_response(url, context, context_instance):
            nt.assert_false(True)
        render_to_response.side_effect = assert_response
        response = Client().get('/some/url/')

我做错了什么?

更新:我想这样做的原因是,在我看来,我呈现的响应如下:

form = SomeFormClass(label_suffix='')
return render_to_response('admin/send_info_message.html', {'form': form,}, context_instance=RequestContext(request))

在我的测试中,我想测试这些参数是否被正确调用,如:

 def assert_response(url, context, context_instance):
     nt.assert_equal('admin/survey_question.html', url)
     nt.assert_equal({'form': SomeForm()}, context)
     nt.assert_equal(RequestContext(response.request), context_instance)

 render_to_response.side_effect = assert_response

I am using Mock and I am not able to patch django's render_to_response function properly. For e.g., the following test never fails:

    from django.test.client import Client
    from mock import patch
    import nose.tools as nt

    @patch('django.shortcuts.render_to_response')
    def test_should_fail(self, render_to_response):
        def assert_response(url, context, context_instance):
            nt.assert_false(True)
        render_to_response.side_effect = assert_response
        response = Client().get('/some/url/')

What am I doing wrong?

Update: The reason I want to do this is that in my view, I am rendering the response like:

form = SomeFormClass(label_suffix='')
return render_to_response('admin/send_info_message.html', {'form': form,}, context_instance=RequestContext(request))

In my test, I want to test that these parameters are correctly called, like:

 def assert_response(url, context, context_instance):
     nt.assert_equal('admin/survey_question.html', url)
     nt.assert_equal({'form': SomeForm()}, context)
     nt.assert_equal(RequestContext(response.request), context_instance)

 render_to_response.side_effect = assert_response

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

謸气贵蔟 2024-11-15 22:26:54

首先,你为什么要这样做?

其次,你应该修补函数的地方就是你调用它的地方 - 即在处理相关 URL 的视图模块中。例如:

@patch('myapp.views.render_to_response')

Firstly, why do you want to do this?

Secondly, the place you should patch a function is the place you are calling it - ie in the views module that handles the relevant URL. For example:

@patch('myapp.views.render_to_response')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文