python - 测试 Django View 时模拟模块

标签 python django unit-testing mocking

我有一个自定义函数来验证请求。我试图在测试期间模拟这个模块,但到目前为止运气不好

这是我的观点

from auth_utils import authenticate_request, UnauthenticatedRequest

def my_view(request):
    try:
        authenticate_request(request)
    except UnauthenticatedRequest:
        return Http404()
    return render(request, 'ok.html', {'status': 'ok'})

在测试中我试图模拟 authenticate_request 所以它不会引发错误

class TestMyView(MyAPITestCase, TestCase):

    @mock.patch('auth_utils.authenticate_request', side_effect=None)
    def setUp(self, mock_auth):
        self.response = self.client.get(reverse('my-view'))

    def test_should_return_ok(self):
        self.assertEqual(self.response.context.get('status'), 'ok')

无法让它工作。有什么建议么 ?

谢谢,Python 2.7,Django 1.8。

最佳答案

您需要在导入的地方模拟函数 authenticate_request,而不是定义的地方。

因此,例如,如果 my_view 定义在 myapp/views.py 中,则 authenticate_request 被导入到 myapp 中。意见。所以你想调用如下内容:

@mock.patch('myapp.views.authenticate_request', side_effect=None)

关于python - 测试 Django View 时模拟模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32066316/

相关文章:

java - 访问私有(private)字段以进行 junit 测试

python - cv2将c++的Range和copyTo函数转换为python

python - 在没有数据库的情况下在 Django 中进行身份验证

python - 我如何跟踪特定帖子的链接并从该帖子中抓取数据

javascript - 单击按钮即可下载图像数组

c++ - 在 C++ 源文件中包含 C++11 头文件

python - Python 中的阿拉伯语 Wordnet 同义词?

python - Pandas 用值列表替换最小值 - 逐行

python - 有没有其他类型的函数可以代替 turtle.goto?

angularjs - AngularJS 的 Karma/Jasmine 中的模拟模块依赖关系