Python 模拟、django 和请求

标签 python django unit-testing mocking django-testing

所以,我刚刚开始在 Django 项目中使用 mock。我正在尝试模拟 View 的一部分,该 View 向远程 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

我如何实现这一目标?

最佳答案

你快到了。你只是稍微错误地调用它。

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

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

关于Python 模拟、django 和请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069541/

相关文章:

python - 从列表中删除 nan - Python

python - 当详细 View 上的force_login() 时,Django Rest Framework 在单元测试中给出 302?

python - Django Rest 框架路由器 url 为空

python - django 模型中每个类别的最新条目

java - 这是集成测试还是单元测试?

python - 在 django 项目中生成此日志文件结构所需的建议

python - 如何使用 Python 将按列嵌套的 CSV 文件转换为嵌套字典?

r - 是否可以在 testthat 中确定测试顺序?

python - 如何使用 python 3.5 将 mysql 数据导入到 .txt 文件?

unit-testing - 测试 Golang 协程