Python模拟,Django和请求 [英] Python mock, django and requests

查看:104
本文介绍了Python模拟,Django和请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我刚刚开始在Django项目中使用模拟.我正在尝试模拟视图的一部分,该视图向远程API发出请求以确认订阅请求是真实的(按照我正在研究的规范进行验证的一种形式).

So, I've just started using mock with a Django project. I'm trying to mock out part of a view which makes a request to a remote API to confirm a subscription request was genuine (a form of verification as per the spec I'm working to).

与我相似:

class SubscriptionView(View):
    def post(self, request, **kwargs):
        remote_url = request.POST.get('remote_url')
        if remote_url:
            response = requests.get(remote_url, params={'verify': 'hello'})

        if response.status_code != 200:
            return HttpResponse('Verification of request failed')

我现在想做的是使用模拟来模拟requests.get调用以更改响应,但是我不知道如何为补丁装饰器做到这一点.我以为你会做类似的事情:

What I now want to do is to use mock to mock out the requests.get call to change the response, but I can't work out how to do this for the patch decorator. I'd thought you do something like:

@patch(requests.get)
def test_response_verify(self):
    # make a call to the view using self.app.post (WebTest), 
    # requests.get makes a suitable fake response from the mock object

我该如何实现?

推荐答案

您快到了.您只是在稍微错误地称呼它.

You're almost there. You're just calling it slightly incorrectly.

from mock import call, patch


@patch('my_app.views.requests')
def test_response_verify(self, mock_requests):
    # We setup the mock, this may look like magic but it works, return_value is
    # a special attribute on a mock, it is what is returned when it is called
    # So this is saying we want the return value of requests.get to have an
    # status code attribute of 200
    mock_requests.get.return_value.status_code = 200

    # Here we make the call to the view
    response = SubscriptionView().post(request, {'remote_url': 'some_url'})

    self.assertEqual(
        mock_requests.get.call_args_list,
        [call('some_url', params={'verify': 'hello'})]
    )

您还可以测试响应的类型正确并且内容正确.

You can also test that the response is the correct type and has the right content.

这篇关于Python模拟,Django和请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆