python - 使用 Mock 修补 render_to_response

标签 python django mocking

我正在使用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

最佳答案

首先,为什么要这样做?

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

@patch('myapp.views.render_to_response')

关于python - 使用 Mock 修补 render_to_response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6095019/

相关文章:

python - 使用推导式将过滤器列表连续应用于 Python 中的集合

javascript - NodeJS 使用 mock-fs 测试 writeFile

python - 在 python 上模拟父类(super class)调用

python - numpy 除法的问题

python - 使用 Django 作为 iOS 应用程序的 API 后端?

python - 在python中的撇号之前删除额外的空间

javascript - 如何将 jQuery 范围 slider 值获取到表单中以存储在 Django 的数据库中

django - PostgreSQL pg_database_size 不同于 pg_total_relation_size 的总和

python - 使用 WSGI 和 apache 安装 django

typescript - 如何创建此 TypeScript 接口(interface)的函数实例?