Last active
February 28, 2024 18:52
-
-
Save adammartinez271828/137ae25d0b817da2509c1a96ba37fc56 to your computer and use it in GitHub Desktop.
Create a mock "open" that will mock open multiple files in sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Nice work!
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)
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
Great!
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. Thanks.