Mock open for unit testing in python

I would like to test, using unittest, a method that reads from a file using the context manager:

with open(k_file, 'r') as content_file:
    content = content_file.read()

      

I don't want to create a file on my system, so I wanted to mock it, but I'm not doing well at the moment. I found mock_open , but I really don't understand how I should use it and feed the mock as content_file in my test case.Here, for example, this post , but I don't understand how I should write this in a test case without changing the source code.

Can anyone point me in the right direction?

+2


source to share


2 answers


mock_open()

- way; you insert open

into your code below the test with the call result mock_open()

:

mocked_open = unittest.mock.mock_open(read_data='file contents\nas needed\n')
with unittest.mock.patch('yourmodule.open', mocked_open, create=True):
    # tests calling your code; the open function will use the mocked_open object

      



patch()

the context manager
will put in your module a open()

global (I named it yourmodule

) bound to the created mocked_open()

object. This object will pretend to create a file object when called.

The only thing this mock file won't do is iterate; you can't do with it for line in content_file

, at least not in current versions of the library mock

. See Setting unittest.mock.mock_open to iterate to work.

+4


source


An alternative is pyfakefs . This allows you to create a fake file system, write and read files, set permissions, etc. without even touching your real disk. It also contains a hands-on example and tutorial showing how to apply pyfakefs for both unittest and doctest.



+1


source







All Articles