如何在 python3 中模拟文件对象

how to mock a file object in python3

在 python2 我的测试方法中有这个:

mock_file = MagicMock(spec=file)

我要转到 python3,但我不知道如何进行类似的模拟。我试过:

from io import IOBase
mock_file = MagicMock(spec=IOBase)

mock_file = create_autospec(IOBase)

我错过了什么?

IOBase 没有实现关键的文件方法,例如 readwrite,因此通常不适合作为创建模拟文件对象的规范。根据您是想模拟原始流、二进制文件还是文本文件,您可以使用 RawIOBaseBufferedIOBaseTextIOBase 作为规范:

from io import BufferedIOBase
mock_file = MagicMock(spec=BufferedIOBase)