Getting the actual return value for mocked file.read ()

I use python-mock to mock an open file. I would like to be able to pass fake data this way, so I can verify that the read() call is being called, as well as using test data without getting into the file system during testing.

Here is what I have so far:

 file_mock = MagicMock(spec=file) file_mock.read.return_value = 'test' with patch('__builtin__.open', create=True) as mock_open: mock_open.return_value = file_mock with open('x') as f: print f.read() 

The result of this is <mock.Mock object at 0x8f4aaec> int 'test' , as I expected. What am I doing wrong in building this layout?

Edit:

It looks like:

 with open('x') as f: f.read() 

and this:

 f = open('x') f.read() 

- different objects. Using the layout as a context manager forces it to return a new Mock , while calling it directly returns everything that I defined in mock_open.return_value . Any ideas?

+4
source share
2 answers

This sounds like a good use case for a StringIO object that already implements the file interface. Perhaps you can do file_mock = MagicMock(spec=file, wraps=StringIO('test')) . Or you could just make your function accept a file-like object and pass it StringIO instead of the real file, avoiding the need for ugly monkey fixes.

Have you looked at the fake documentation?

http://www.voidspace.org.uk/python/mock/compare.html#mocking-the-builtin-open-used-as-a-context-manager

+9
source

In Python 3, the template is simple:

 >>> import unittest.mock as um >>> with um.patch('builtins.open', um.mock_open(read_data='test')): ... with open('/dev/null') as f: ... print(f.read()) ... test >>> 

(Yes, you can even mock / dev / null return the contents of the file.)

+6
source

Source: https://habr.com/ru/post/1389513/


All Articles