2

In python2 I have this in my test method:

mock_file = MagicMock(spec=file)

I'm moving to python3, and I can't figure out how to do a similar mock. I've tried:

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

mock_file = create_autospec(IOBase)

What am I missing?

zli
  • 307
  • 1
  • 12

1 Answers1

4

IOBase does not implement crucial file methods such as read and write and is therefore usually unsuitable as a spec to create a mocked file object with. Depending on whether you want to mock a raw stream, a binary file or a text file, you can use RawIOBase, BufferedIOBase or TextIOBase as a spec instead:

from io import BufferedIOBase
mock_file = MagicMock(spec=BufferedIOBase)
blhsing
  • 91,368
  • 6
  • 71
  • 106