如何模拟在python中为特定路径打开的文件?



所以我知道在我的单元测试中我可以模拟上下文管理器open(),即:

with open('file_path', 'r') as stats:

与嘲笑

with mock.patch('builtins.open', mock.mock_open(read_data=mock_json)):

但是是否有一种方法可以让我只模拟它的特定文件路径?或者可能有其他方法来确保上下文管理器在单元测试中用正确的路径调用?

要仅为特定路径模拟open,必须提供自己的模拟对象,该对象根据路径不同以不同的方式处理open。假设我们有一个函数:

def do_open(path):
with open(path, "r") as f:
return f.read()

open模拟为返回一个内容为"bar"如果path是"foo",但其他方面正常工作,您可以这样做:

from unittest import mock
from my_module.do_open import do_open
builtin_open = open  # save the unpatched version
def mock_open(*args, **kwargs):
if args[0] == "foo":
# mocked open for path "foo"
return mock.mock_open(read_data="bar")(*args, **kwargs)
# unpatched version for every other path
return builtin_open(*args, **kwargs)
@mock.patch("builtins.open", mock_open)
def test_open():
assert do_open("foo") == "bar"
assert do_open(__file__) != "bar"

如果您不想将原始的open保存在全局变量中,您也可以将其包装到一个类中:

class MockOpen:
builtin_open = open
def open(self, *args, **kwargs):
if args[0] == "foo":
return mock.mock_open(read_data="bar")(*args, **kwargs)
return self.builtin_open(*args, **kwargs)
@mock.patch("builtins.open", MockOpen().open)
def test_open():
...

相关内容

  • 没有找到相关文章

最新更新