我想测试一个 Python 函数,它读取一个 gzip 文件并从文件中提取一些东西(使用 pytest)。
import gzip
def my_function(file_path):
output = []
with gzip.open(file_path, 'rt') as f:
for line in f:
output.append('something from line')
return output
Run Code Online (Sandbox Code Playgroud)
我可以创建一个像我可以传递给的对象的 gzip 文件my_function吗?该对象应已定义内容并应与gzip.open()
我知道我可以在夹具中创建一个临时 gzip 文件,但这取决于文件系统和环境的其他属性。从代码创建一个类似文件的对象会更便携。
import io, gzip
def inmem():
stream = io.BytesIO()
with gzip.open(stream, 'wb') as f:
f.write(b'spam\neggs\n')
stream.seek(0)
return stream
Run Code Online (Sandbox Code Playgroud)