Skip to content

Instantly share code, notes, and snippets.

@adammartinez271828
Last active February 28, 2024 18:52
Show Gist options
  • Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.
Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.
Create a mock "open" that will mock open multiple files in sequence
from unittest.mock import mock_open
def multi_mock_open(*file_contents):
"""Create a mock "open" that will mock open multiple files in sequence
Args:
*file_contents ([str]): a list of file contents to be returned by open
Returns:
(MagicMock) a mock opener that will return the contents of the first
file when opened the first time, the second file when opened the
second time, etc.
"""
mock_files = [mock_open(read_data=content).return_value for content in file_contents]
mock_opener = mock_open()
mock_opener.side_effect = mock_files
return mock_opener
@mrwizard82d1
Copy link

mrwizard82d1 commented Aug 6, 2020

Nice. Thanks.

@mattskone
Copy link

Nice work!

@mszaf
Copy link

mszaf commented Dec 30, 2020

Thanks for making this easy!

For those that may be unfamiliar with unpacking:

file_content_list = ['file_1_content', 'file_2_content']

# Do this
multi_mock_open(*file_content_list)

# Not this
multi_mock_open(file_content_list)

@didib
Copy link

didib commented Jan 6, 2021

Thanks, this was useful. I eventually came up with this:

builtin_open = open

def mapped_mock_open(file_contents_dict):
    """Create a mock "open" that will mock open multiple files based on name
    Args:
        file_contents_dict: A dict of 'fname': 'content'
    Returns:
        A Mock opener that will return the supplied content if name is in
        file_contents_dict, otherwise the builtin open
    """
    mock_files = {}
    for fname, content in file_contents_dict.items():
        mock_files[fname] = mock_open(read_data=content).return_value

    def my_open(fname, *args, **kwargs):
        if fname in mock_files:
            return mock_files[fname]
        else:
            return builtin_open(fname, *args, **kwargs)

    mock_opener = mock.Mock()
    mock_opener.side_effect = my_open
    return mock_opener

@rubenobbink
Copy link

Great!

@ang-d
Copy link

ang-d commented Feb 22, 2022

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment