Mocking open(file_name) in unit tests

前端 未结 8 1837
慢半拍i
慢半拍i 2020-12-05 00:37

I have a source code that opens a csv file and sets up a header to value association. The source code is given below:

def ParseCsvFile(source): 
  \"\"\"Pa         


        
8条回答
  •  难免孤独
    2020-12-05 01:00

    This is admittedly an old question, hence some of the answers are outdated.

    In the current version of the mock library there is a convenience function designed for precisely this purpose. Here's how it works:

    >>> from mock import mock_open
    >>> m = mock_open()
    >>> with patch('__main__.open', m, create=True):
    ...     with open('foo', 'w') as h:
    ...         h.write('some stuff')
    ...
    >>> m.mock_calls
    [call('foo', 'w'),
     call().__enter__(),
     call().write('some stuff'),
     call().__exit__(None, None, None)]
    >>> m.assert_called_once_with('foo', 'w')
    >>> handle = m()
    >>> handle.write.assert_called_once_with('some stuff')
    

    Documentation is here.

提交回复
热议问题