首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在全局范围内定义自动屋修补程序?

如何在全局范围内定义自动屋修补程序?
EN

Stack Overflow用户
提问于 2020-05-03 21:07:28
回答 1查看 1.4K关注 0票数 7

现在,我在几个模拟第三方API的测试中这样做:

代码语言:javascript
复制
@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次,并可能会增加更多在未来。我想在我所有的测试中在全球范围内嘲弄这个问题。

我在医生们中看到了这个例子:

代码语言:javascript
复制
@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测试中使用类。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-04 04:53:55

你可以用:

代码语言:javascript
复制
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)

夹具的寿命与每个功能一样长,因此在每个功能的末尾都会恢复补丁。

请注意,在本例中不需要生成模拟,但是如果我们想在某些测试用例中更改模拟,则可以访问它:

代码语言:javascript
复制
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,它将是:

代码语言:javascript
复制
@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)
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61581645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档