【发布时间】:2019-11-06 14:08:37
【问题描述】:
在我们的 repo 中,我们有一些对 s3 的调用。我们从不希望这些在测试期间执行,所以我们在每个单独的测试中模拟它们,这很烦人。这是大量重复的代码,如果开发人员忘记在运行测试之前编写模拟代码,可能会很危险。
我想编写一个 pytest 夹具,自动将模拟应用到每个测试函数。也就是说,我想改变我的代码看起来像这样:
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
这可能吗?
【问题讨论】:
标签: python mocking pytest decorator fixtures