How to mock ‘open’ built-in function

Here is a code snippet on how to test open built-in function:

Code to test:

def my_function(self, id: int) -> None:
    file_path = 'path/to/files/{}.txt'.format(id)
    with open(file_path, 'w') as f:
        f.write('< My data >')


Unit test:

def test_my_function(self):
    _open = mock.mock_open()	
    with mock.patch('', _open, create=True): # noqa
    _open.assert_called_with('path/to/files/123.txt', 'w')
    fp = _open.return_value.__enter__.return_value
    fp.write.assert_called_with('< My data >')


Happy unit testing.


Leave a Reply

Your email address will not be published.