如何模拟遗留函数的文件名以提供内存中已有的数据



我想使用一个接收文件名作为参数的遗留函数。该函数将在打开该文件后进行一些处理。

def legacy_f(filename):
with open(filename, 'r') as fh:
# some processing

但我希望处理发生在一些已经加载在某个变量中的数据中,而不是在文件中。由于性能原因,先将数据保存到文件不是解决方案。有没有办法";傻瓜;让它认为是在打开一个文件的遗留函数?

我的情况正是这个问题中的情况,但公认的答案建议使用tempfile.NamedTemporaryFile,(我相信(它确实在磁盘中创建了一个文件。我负担不起。

这有点麻烦,可能不是一个好的做法,但你可以在上下文管理器中对打开的函数进行猴子补丁。这不会取代open,只是简单地用上下文管理器中的其他东西来修补它。您可以看到,如果我再次调用该函数,但在上下文管理器之外,它会恢复为使用内置的open。

然而,这种类型的嘲讽通常用于测试。

from unittest import mock

def legacy_f(filename):
with open(filename, 'r') as fh:
for line in fh:
print(line, end="")
print()
data = "thisnisnsomendata"
filename = "somefile"
#patch the open call
with mock.patch('builtins.open', mock.mock_open(read_data=data)):
legacy_f(filename)
#the patch only works in the conext manager, outside its the normal open
try:
legacy_f(filename)
except FileNotFoundError:
print(f"file '{filename}' not found since we only patch in the context manager")

输出

this
is
some
data
file 'somefile' not found since we only patch in the context manager

最新更新