相关疑难解决方法(0)

为什么最简单的 requests_mock 示例在使用 pytest 时失败?

我有一个特殊的问题requests_mock。我想用它pytest来测试我的 API 包装器库。

我尝试使用requests_mock docs 中第一个示例,除了我将它放在test_mock() -function 中并添加了一个assert-statement 供 pytest 发现它。

以下代码失败:

# tests/test_mock.py

import requests
import requests_mock

with requests_mock.Mocker() as m:
    def test_mock():
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'
Run Code Online (Sandbox Code Playgroud)

但是,在 ipython 中运行以下示例时,它按预期工作。这是示例中的确切代码:

with requests_mock.Mocker() as m:
    m.get('http://test.com', text='resp')
    print(requests.get('http://test.com').text)

# prints 'resp'
Run Code Online (Sandbox Code Playgroud)

因为我可以requests_mock从 ipython 工作,所以我认为问题出在 pytest 上,但我可能是错的。

似乎根本没有使用适配器,因此请求会向目标 url 发送一个真正的 http 请求,而不是使用模拟对象。


我正在使用 Python 3.6.3 (Anaconda3)、requests_mock 1.3.0 和 pytest 3.3.0

运行失败的代码的输出:

C:\dev\mylib>pytest -v …
Run Code Online (Sandbox Code Playgroud)

python mocking pytest python-requests

5
推荐指数
1
解决办法
4092
查看次数

单元测试python请求?

我有几个方法我想使用Python requests库进行单元测试.从本质上讲,他们正在做这样的事情:

def my_method_under_test(self):
    r = requests.get("https://ec2.amazonaws.com/", params={'Action': 'GetConsoleOutput',
            'InstanceId': 'i-123456'})
    # do other stuffs
Run Code Online (Sandbox Code Playgroud)

我基本上希望能够测试它

  1. 它实际上是在提出请求.
  2. 它使用的是GET方法.
  3. 它使用正确的参数.
  4. 等等

问题是,我希望能够在不实际提出请求的情况下对此进行测试,因为它需要太长时间,而且某些操作可能具有破坏性.

我怎样才能快速轻松地模拟和测试?

python unit-testing mocking python-requests

2
推荐指数
1
解决办法
2869
查看次数

标签 统计

mocking ×2

python ×2

python-requests ×2

pytest ×1

unit-testing ×1