Python testing: using a fake file with mock & io.StringIO

Just mock out both os.path.isfile and the open() call, and pass in a fake filename (you are not expected to pass in an open file, after all).

The mock library includes a utility for the latter: mock_open():

@mock.patch('os.path.isfile')
def test_CheckConfig_with_file(mock_isfile):
    mock_isfile.return_value = True
    config_data = mock.mock_open(read_data='data')
    with mock.patch('mymodule.open', config_data) as mock_open:
        expected = parsed_file_data
        actual = CheckConfig('mocked/filename').config
        assert expected == actual

This causes the if isinstance(data, list): test to be false (because data is a string instead), followed by the elif os.path.isfile(data): returning True, and the open(data) call to use your mocked data from the mock_open() result.

You can use the mock_open variable to assert that open() was called with the right data (mock_open. assert_called_once_with('mocked/filename') for example).

Demo:

>>> import os.path
>>> from unittest import mock
>>> class CheckConfig(object):
...     def __init__(self, config):
...         self.config = self._check_input_data(config)
...     def _check_input_data(self, data):
...         if isinstance(data, list):
...             return self._parse(data)
...         elif os.path.isfile(data):
...             with open(data) as f:
...                 return self._parse(f.readlines())
...     def _parse(self, data):
...         return data
...
>>> with mock.patch('os.path.isfile') as mock_isfile:
...     mock_isfile.return_value = True
...     config_data = mock.mock_open(read_data='line1\nline2\n')
...     with mock.patch('__main__.open', config_data) as mock_open:
...         actual = CheckConfig('mocked/filename').config
...
>>> actual
['line1\n', 'line2\n']
>>> mock_open.mock_calls
[call('mocked/filename'),
 call().__enter__(),
 call().readlines(),
 call().__exit__(None, None, None)]

In case you end up here wondering how to solve this using the pytest-mock library, here is how you do it:

def test_open(mocker):
    m = mocker.patch('builtins.open', mocker.mock_open(read_data='bibble'))
    with open('foo') as h:
        result = h.read()

    m.assert_called_once_with('foo')
    assert result == 'bibble'

This code example was found (but had to be adjusted) here.