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('my_project.scripts.my_script.open', _open, create=True): # noqa
        my_function(1)
  
    _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. Required fields are marked *