zli*_*zli 2 python mocking python-2.7 python-3.x magicmock
在 python2 中,我的测试方法中有这样的内容:
mock_file = MagicMock(spec=file)
Run Code Online (Sandbox Code Playgroud)
我正在转向 python3,但我不知道如何进行类似的模拟。我试过了:
from io import IOBase
mock_file = MagicMock(spec=IOBase)
mock_file = create_autospec(IOBase)
Run Code Online (Sandbox Code Playgroud)
我缺少什么?
IOBase不实现关键的文件方法,例如read和write,因此通常不适合作为创建模拟文件对象的规范。根据您想要模拟原始流、二进制文件还是文本文件,您可以使用RawIOBase,BufferedIOBase或TextIOBase作为规范:
from io import BufferedIOBase
mock_file = MagicMock(spec=BufferedIOBase)
Run Code Online (Sandbox Code Playgroud)