python - 是否可以编写将模拟装饰器应用于函数的函数级 pytest fixture ?

标签 python mocking pytest decorator fixtures

在我们的 repo 中,我们有一些对 s3 的调用。我们从不希望这些在测试期间执行,所以我们在每个单独的测试中模拟它们,这很烦人。这是很多重复的代码,如果开发人员忘记在运行测试之前编写模拟,可能会很危险。

我想编写一个 pytest fixture,自动将 mock 应用于每个测试函数。也就是说,我想将我的代码更改为如下所示:

test_file.py:

@mock.patch.object(S3Hook, 'write_to_s3')
def test1(_):
    # test some stuff without writing to s3

@mock.patch.object(S3Hook, 'write_to_s3')
def test2(_):
    # test some more stuff without writing to s3

为此:

conftest.py:

@pytest.fixture(scope='function', autouse=True)
def mock_out_s3(request):
    # somehow apply the mock.patch.object decorator to request.function here


test_file.py:

def test1():
    # test some stuff; the mock is automatically applied, so we won't write to s3

def test2():
    # ditto

这可能吗?

最佳答案

发布我如何让它工作的详细信息(基于 ParthS007 的回答)以帮助将来尝试做同样事情的其他人:

@pytest.fixture(scope='function', autouse=True)
def mock_out_s3(request):
    patcher = mock.patch.object(S3Hook, 'write_to_s3')
    patcher.start()
    request.addfinalizer(patcher.stop)

关于python - 是否可以编写将模拟装饰器应用于函数的函数级 pytest fixture ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56742139/

相关文章:

reactjs - React 测试库和 Jest 中的模拟路由器

java - 线程 "main"java.lang.NoClassDefFoundError : org/mockito/Mockito 中的异常

python - 自定义 sys.excepthook 不适用于 pytest

python - 需要 py.test 在 python 日志记录模块的日志文件中记录断言错误

python - 检查字符串列表和列表是否为空

ruby-on-rails - rspec 版本 2.14 的未定义方法 `rspec_reset'

python - 在 python 中使用 *args 和默认参数

python - 是否可以让 pytest 在每次测试执行后调用 webhook?

python - 如何使用 pyqt4 在 TreeView 中搜索项目名称

python - 在 matplotlibs 交互模式下编辑 python 变量