现在,我在几个模拟第三方API的测试中这样做:
@patch("some.api.execute")
def sometest(
mock_the_api, blah, otherstuff
):
mock_the_api.return_value = "mocked response"
my_func_that_uses_api(blah, otherstuff)这可以防止my_func_that_uses_api() (它调用API)进行实际的出站调用。但我这样做了4-5次,并可能会增加更多在未来。我想在我所有的测试中在全球范围内嘲弄这个问题。
我在医生们中看到了这个例子:
@pytest.fixture(autouse=True)
def no_requests(monkeypatch):
"""Remove requests.sessions.Session.request for all tests."""
monkeypatch.delattr("requests.sessions.Session.request")除了修补API响应之外,我如何做到这一点呢?
我尝试了monkeypatch.patch("some.api.execute"),但得到了错误AttributeError: 'MonkeyPatch' object has no attribute 'patch'
另外,我不想在我的pytest测试中使用任何类(比如测试用例)--我现在想避免在pytest测试中使用类。
发布于 2020-05-04 04:53:55
你可以用:
from unittest import mock
import pytest
@pytest.fixture(autouse=True)
def my_api_mock():
with mock.patch("some.api.execute") as api_mock:
api_mock.return_value = "mocked response"
yield api_mock
def test_something(blah, otherstuff):
my_func_that_uses_api(blah, otherstuff)夹具的寿命与每个功能一样长,因此在每个功能的末尾都会恢复补丁。
请注意,在本例中不需要生成模拟,但是如果我们想在某些测试用例中更改模拟,则可以访问它:
def test_something(blah, otherstuff):
my_func_that_uses_api(blah, otherstuff)
def test_something_else(my_api_mock, blah, otherstuff):
my_api_mock.return_value = "other response for this test"
my_func_that_uses_api(blah, otherstuff)为了完整起见,如果没有auto-use,它将是:
@pytest.fixture
def my_api_mock():
with mock.patch("some.api.execute") as api_mock:
api_mock.return_value = "mocked response"
yield api_mock
def test_something(my_api_mock, blah, otherstuff):
my_func_that_uses_api(blah, otherstuff)https://stackoverflow.com/questions/61581645
复制相似问题