使用 Mock 修补 render_to_response
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,你为什么要这样做?
其次,你应该修补函数的地方就是你调用它的地方 - 即在处理相关 URL 的视图模块中。例如:
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: