如何在单元测试中断言写入io.BytesIO的内容



假设以下最小代码:

def upload(fileobj, key):
# e.g. S3.Bucket.upload_fileobj()
pass
def work():
with io.BytesIO() as tmp:
tmp.write(b'abc')  # here can be a tarfile created
upload(tmp, "file")

我想在单元测试中断言tmp的内容。如何正确操作?

这种方式不起作用:

from unittest.mock import MagicMock
upload = MagicMock()
work()
with upload.mock_calls[0][1][0] as f:
f.readlines() # ValueError: I/O operation on closed file.

我自己想出了一个解决方案(感谢Tim Roberts在评论中的启发(,那就是使用(unittest.mock.MagicMock构造函数的(side_effect选项。

import unittest.mock
eavesdropped = []
def upload_mock(fileobj, key):
fileobj.seek(0)
eavesdropped.append(fileobj.read())
with unittest.mock.patch('__main__.upload', side_effect=upload_mock) as upl:
work()
assert eavesdropped[0] == b'abc'
work()
assert eavesdropped[1] == b'abc'

相关内容

  • 没有找到相关文章

最新更新