【问题标题】:Python mock, django and requestsPython 模拟、django 和请求
【发布时间】:2013-04-10 18:37:47
【问题描述】:

所以,我刚刚开始在 Django 项目中使用 mock。我正在尝试模拟视图的一部分,该视图向远程 API 发出请求以确认订阅请求是真实的(根据我正在努力的规范的一种验证形式)。

我所拥有的类似于:

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')

我现在想做的是使用 mock 来模拟 requests.get 调用以更改响应,但我不知道如何为补丁装饰器执行此操作。我以为你会这样做:

@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

我如何做到这一点?

【问题讨论】:

  • 死机使用模拟?还有 django.test.client.RequestFactory - docs.djangoproject.com/en/1.5/topics/testing/advanced/…
  • 只是为了将来的观众,提问者想模拟一个外部 API 调用。不是对视图本身的调用。在这种情况下,模拟似乎非常明智。
  • 根据@aychedee,这确实是我提出这个问题的目标。

标签: python django unit-testing mocking django-testing


【解决方案1】:

你快到了。你只是稍微不正确地调用它。

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'})]
    )

您还可以测试响应的类型是否正确,内容是否正确。

【讨论】:

    【解决方案2】:

    都在the documentation:

    patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)

    target 应该是“package.module.ClassName”形式的字符串。

    from mock import patch
    
    # or @patch('requests.get')
    @patch.object(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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 2011-01-03
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多