mock file open in python

In order to mock file open in python, we can use the unittest.mock module. Specifically, we can use the patch decorator to replace the built-in open() function with a mock version.

Here's an example of how to mock file open:

main.py
from unittest.mock import patch

def test_my_function():
    # create a mock file object
    mock_file = MagicMock()

    # configure the mock to return some data when read
    mock_file.read.return_value = "Hello, World!"

    # patch the built-in 'open' function to return the mock object
    with patch('builtins.open', return_value=mock_file) as mock_open:
        # call my function that uses 'open'
        result = my_function()

    # make assertions about the result
    assert result == "Hello, World!"
    mock_file.read.assert_called_once()
    mock_open.assert_called_once_with('my_file.txt', 'r')
611 chars
19 lines

In this example, we create a mock file object using MagicMock(). We then use the return_value attribute to specify what data the mock should return when its read() method is called.

We then use the patch decorator to replace the built-in open() function with a mock version that returns our mock file object. We pass the name of the function to patch as a string as the first argument to patch.

Inside the with block, any call to open() will now return our mock file object instead of the built-in function. We can then make assertions about how our function interacts with the file object, such as calling read() once and opening the file with the correct arguments.

gistlibby LogSnag