zli
zli

Reputation: 327

how to mock a file object in python3

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?

Upvotes: 2

Views: 1596

Answers (1)

blhsing
blhsing

Reputation: 107124

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)

Upvotes: 5

Related Questions